@sazabi/cli 0.24.0 → 0.25.0-dev.gac76330

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.
Files changed (2) hide show
  1. package/dist/index.js +2 -2
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -8746,10 +8746,10 @@ _sazabi() {
8746
8746
  }
8747
8747
 
8748
8748
  complete -F _sazabi sazabi
8749
- `.trim();var OxA=async(A)=>{let{values:t}=F(A,{json:{type:"boolean"}}),g=orA();if(t.json){X({shell:"zsh",script:g});return}console.log(g)},zxA=async(A)=>{let{values:t}=F(A,{json:{type:"boolean"}}),g=erA();if(t.json){X({shell:"bash",script:g});return}console.log(g)},QrA=nA("completions","Shell completion scripts").withSubcommands({zsh:L("zsh","Output zsh completion script",OxA).withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(['eval "$(sazabi completions zsh)" # Add to .zshrc']).build(),bash:L("bash","Output bash completion script",zxA).withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(['eval "$(sazabi completions bash)" # Add to .bashrc']).build()}).withExamples(['eval "$(sazabi completions zsh)" # Enable zsh completions','eval "$(sazabi completions bash)" # Enable bash completions']).build();iA();uA();CA();var hrA={id:{label:"ID",type:{kind:"string"}},projectId:{label:"Project",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},currentStatus:{label:"Status",type:{kind:"string"}},description:{label:"Description",type:{kind:"nullable-string"}},origin:{label:"Origin",type:{kind:"string"}},lifecycle:{label:"Lifecycle",type:{kind:"string"}},observationState:{label:"Observation",type:{kind:"string"}},registryRevision:{label:"Revision",type:{kind:"number"}},canonicalComponentId:{label:"Canonical component",type:{kind:"id"}},mergedIntoComponentId:{label:"Merged into",type:{kind:"nullable-string"}},firstSeenAt:{label:"Created at",type:{kind:"date"}},lastSeenAt:{label:"Last seen",type:{kind:"date"}},deletedAt:{label:"Deleted at",type:{kind:"nullable-date"}},retiredAt:{label:"Retired at",type:{kind:"nullable-date"}},retirementReason:{label:"Retirement reason",type:{kind:"nullable-string"}},legacyStateUnknown:{label:"Legacy inactive",type:{kind:"boolean"}}},mxA={schema:hrA,columns:["id","name","lifecycle","observationState","currentStatus"],jsonFields:["id","projectId","name","currentStatus","description","origin","lifecycle","observationState","registryRevision","canonicalComponentId","mergedIntoComponentId","firstSeenAt","lastSeenAt","deletedAt","retiredAt","retirementReason","legacyStateUnknown"],emptyMessage:"No components found. Register one with 'sazabi components register --name <name>'."},Bv={layout:"field-list",schema:hrA,fields:["id","projectId","name","currentStatus","description","origin","lifecycle","observationState","registryRevision","canonicalComponentId","mergedIntoComponentId","firstSeenAt","lastSeenAt","deletedAt","retiredAt","retirementReason","legacyStateUnknown"],title:"Component"},WxA={status:{label:"Status",type:{kind:"string"}},componentId:{label:"Component ID",type:{kind:"id"}},sourceType:{label:"Source type",type:{kind:"string"}},withdrawn:{label:"Withdrawn",type:{kind:"boolean"}}},ZxA={layout:"field-list",schema:WxA,fields:["status","componentId","sourceType","withdrawn"],title:"Component observation"},VxA=(A)=>{let t=A,g=Object.values(t.counts).reduce((i,n)=>i+n,0);return`${t.canonicalComponentName} (${t.canonicalComponentId}); ${t.affectedComponentIds.length} component(s), ${g} dependent(s); no changes applied`},jxA={status:{label:"Status",type:{kind:"string"}},preview:{label:"Retirement preview",type:{kind:"custom",render:VxA,serialize:(A)=>A}}},HxA={layout:"field-list",schema:jxA,fields:["status","preview"],title:"Retirement confirmation required"},ta=(A,t,g)=>{if(A===void 0)return;try{let i=JSON.parse(A);if(!i||typeof i!=="object"||Array.isArray(i))throw Error("must be a JSON object");return i}catch(i){let n=`${t} must be valid JSON: ${i instanceof Error?i.message:String(i)}`;if(g)return u(n);return D(n)}},hv=(A)=>A?A.split(",").map((t)=>t.trim()).filter(Boolean):[],cv={kind:"custom",render:(A)=>JSON.stringify(A,null,2),serialize:(A)=>A},XxA={preview:{label:"Preview",type:cv}},KxA={layout:"field-list",schema:XxA,fields:["preview"],title:"Component operation preview"},_xA={result:{label:"Result",type:cv}},sxA={layout:"field-list",schema:_xA,fields:["result"],title:"Component operation result"},Zb=(A,t)=>W(KxA,A,{json:t}),Vb=(A,t)=>W(sxA,A,{json:t}),xxA=async(A)=>{let t=R({tokenFlag:A.token,jsonMode:A.json}),g=f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=l(await g.components.list({limit:A.limit,cursor:A.cursor,includeDeleted:A.includeDeleted}),"Couldn't list components (check the active project and try again)",A.json);s(mxA,i.components,{json:A.json,nextCursor:i.nextCursor})},qxA=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.components.get(A),"Couldn't get component (run 'sazabi components list' to see component IDs)",t.json);W(Bv,n.component,{json:t.json})},dxA=async(A)=>{let t=A.name?.trim(),g=A.description?.trim(),i=A.origin?.trim();if(!t){if(A.json)return u("Name is required.");return D("Name is required.")}if(A.description!==void 0&&!g){if(A.json)return u("Description cannot be empty.");return D("Description cannot be empty.")}if(i!==void 0&&i!=="code_detected"&&i!=="log_observed"){if(A.json)return u("Invalid origin. Use 'code_detected' (inferred from code) or 'log_observed' (inferred from telemetry).");return D("Invalid origin. Use 'code_detected' (inferred from code) or 'log_observed' (inferred from telemetry).")}let n=R({tokenFlag:A.token,jsonMode:A.json}),o=f({token:n.token,organizationId:n.organizationId,projectId:n.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),e=l(await o.components.register({name:t,...g?{description:g}:{},...i?{origin:i}:{}}),"Failed to register component",A.json);W(Bv,e.component,{json:A.json})},pxA=async(A,t)=>{let g=t.reason?.trim();if(t.reason!==void 0&&!g){if(t.json)return u("Reason cannot be empty.");return D("Reason cannot be empty.")}let i=R({tokenFlag:t.token,jsonMode:t.json}),n=f({token:i.token,organizationId:i.organizationId,projectId:i.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),o=l(await n.components.deregister(A,g),"Failed to deregister component",t.json);if(o.status==="observation_withdrawn"){W(ZxA,o,{json:t.json});return}W(HxA,o,{json:t.json})},kB=(A)=>{let t=R({tokenFlag:A.token,jsonMode:A.json});return f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json})},A3A=async(A,t)=>{let g=t.name?.trim(),i=t.reason?.trim();if(!g){if(t.json)return u("Name is required.");return D("Name is required.")}if(!t.requestId){if(t.json)return u("Request ID is required.");return D("Request ID is required.")}if(!i){if(t.json)return u("Reason is required.");return D("Reason is required.")}let n=kB(t),o=l(await n.components.rename({componentId:A,name:g,requestId:t.requestId,reason:i}),"Failed to rename component",t.json);W(Bv,o.component,{json:t.json})},t3A=async(A,t)=>{let g=kB(t),i=ta(t.confirmPreviewRevision,"Confirm preview revision",t.json);if(!i){let e=l(await g.components.retirementPreview({componentId:A}),"Failed to preview component retirement",t.json);Zb(e,t.json);return}let n=t.reason?.trim();if(!t.requestId||!n){if(t.json)return u("Commit requires --request-id and --reason with --confirm-preview-revision.");return D("Commit requires --request-id and --reason with --confirm-preview-revision.")}let o=l(await g.components.retire({componentId:A,requestId:t.requestId,reason:n,componentRevisions:i,confirmCanonicalGroup:t.confirmCanonicalGroup??!1}),"Failed to retire component; refresh the preview if it changed",t.json);Vb(o,t.json)},g3A=async(A,t)=>{let g=kB(t),i=ta(t.confirmPreviewRevision,"Confirm preview revision",t.json);if(!i){let e=l(await g.components.restorationPreview({componentId:A,...t.retirementOperationId?{retirementOperationId:t.retirementOperationId}:{}}),"Failed to preview component restoration",t.json);Zb(e,t.json);return}let n=t.reason?.trim();if(!t.requestId||!t.retirementOperationId||!n){if(t.json)return u("Commit requires --request-id, --retirement-operation-id, and --reason with --confirm-preview-revision.");return D("Commit requires --request-id, --retirement-operation-id, and --reason with --confirm-preview-revision.")}let o=l(await g.components.restore({componentId:A,retirementOperationId:t.retirementOperationId,requestId:t.requestId,reason:n,componentRevisions:i,selections:{notificationRuleIds:hv(t.notificationRuleIds),automationBindingIds:hv(t.automationBindingIds),recommendationScopeIds:[],relationshipIds:hv(t.relationshipIds)}}),"Failed to restore component; refresh the preview if it changed",t.json);Vb(o,t.json)},n3A=async(A)=>{if(!A.sourceComponentId||!A.targetComponentId){if(A.json)return u("Source and target component IDs are required.");return D("Source and target component IDs are required.")}let t=kB(A),g={sourceComponentId:A.sourceComponentId,targetComponentId:A.targetComponentId},i=ta(A.confirmPreviewRevision,"Confirm preview revision",A.json);if(!i){let I=l(await t.components.mergePreview(g),"Failed to preview component consolidation",A.json);Zb(I,A.json);return}let n=A.reason?.trim(),o=ta(A.policyDispositions,"Policy dispositions",A.json);if(!A.requestId||!n||!o){if(A.json)return u("Commit requires --request-id, --reason, and --policy-dispositions with --confirm-preview-revision.");return D("Commit requires --request-id, --reason, and --policy-dispositions with --confirm-preview-revision.")}let e=l(await t.components.merge({...g,requestId:A.requestId,reason:n,componentRevisions:i,policyDispositions:o,confirmPolicyImpact:A.confirmPolicyImpact??!1}),"Failed to consolidate component; refresh the preview if it changed",A.json);Vb(e,A.json)},i3A=async(A)=>{let t=kB(A),g=l(await t.components.relationships.list({includeHistorical:A.includeHistorical}),"Failed to list component relationships",A.json);W({layout:"field-list",schema:{relationships:{label:"Relationships",type:cv}},fields:["relationships"],title:"Component relationships"},g,{json:A.json})},o3A=async(A,t)=>{if(!t.sourceComponentId||!t.targetComponentId||t.relationshipType!=="part_of"&&t.relationshipType!=="depends_on"){if(t.json)return u("Source, target, and relationship type (part_of or depends_on) are required.");return D("Source, target, and relationship type (part_of or depends_on) are required.")}let g=kB(t),i={action:A,sourceComponentId:t.sourceComponentId,targetComponentId:t.targetComponentId,relationshipType:t.relationshipType},n=ta(t.confirmPreviewRevision,"Confirm preview revision",t.json);if(!n){let h=l(await g.components.relationships.preview(i),"Failed to preview component relationship",t.json);Zb(h,t.json);return}let o=t.reason?.trim();if(!t.requestId||!o){if(t.json)return u("Commit requires --request-id and --reason with --confirm-preview-revision.");return D("Commit requires --request-id and --reason with --confirm-preview-revision.")}let e={sourceComponentId:i.sourceComponentId,targetComponentId:i.targetComponentId,relationshipType:i.relationshipType,requestId:t.requestId,reason:o,componentRevisions:n,confirmPolicyImpact:t.confirmPolicyImpact??!1},I=l(A==="add"?await g.components.relationships.add(e):await g.components.relationships.remove(e),`Failed to ${A} component relationship; refresh the preview if it changed`,t.json);Vb(I,t.json)},mb={...m,"confirm-preview-revision":{type:"string"},"request-id":{type:"string"},reason:{type:"string"}},Wb={...z,"confirm-preview-revision":{type:"string",description:"Exact componentRevisions JSON from the preview; omit to preview only"},"request-id":{type:"string",description:"Project-scoped UUID idempotency key required for commit"},reason:{type:"string",description:"Audit reason required for commit"}},IrA=(A)=>L(A,`${A==="add"?"Add":"End"} a component relationship`,async(t)=>{let{values:g}=F(t,{...mb,source:{type:"string"},target:{type:"string"},type:{type:"string"},"confirm-policy-impact":{type:"boolean"}});await o3A(A,{token:g.token,json:g.json,apiBaseUrl:g["api-base-url"],sourceComponentId:g.source,targetComponentId:g.target,relationshipType:g.type,confirmPreviewRevision:g["confirm-preview-revision"],requestId:g["request-id"],reason:g.reason,confirmPolicyImpact:g["confirm-policy-impact"]})}).withOptions({...Wb,source:{type:"string",description:"Source component ID"},target:{type:"string",description:"Target component ID"},type:{type:"string",description:"Relationship type: part_of or depends_on"},"confirm-policy-impact":{type:"boolean",description:"Confirm the policy-scope delta shown by the preview"}}).withExamples([`sazabi components relationships ${A} --source <component-id> --target <component-id> --type part_of # Preview a parent-child topology change`]).build(),e3A=nA("relationships","Inspect and edit component topology").withSubcommands({list:L("list","List component relationships",async(A)=>{let{values:t}=F(A,{...m,"include-historical":{type:"boolean"}});await i3A({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],includeHistorical:t["include-historical"]})}).withOptions({...z,"include-historical":{type:"boolean",description:"Include historically ended relationships"}}).build(),add:IrA("add"),remove:IrA("remove")}).build(),BrA=nA("components","Manage status page components").withSubcommands({list:L("list","List components in the active project",async(A)=>{let{values:t}=F(A,{...m,limit:{type:"string"},cursor:{type:"string"},"include-deleted":{type:"boolean"}});await xxA({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],limit:t.limit?Number(t.limit):void 0,cursor:t.cursor,includeDeleted:t["include-deleted"]})}).withOptions({...z,limit:{type:"string",description:"Maximum number of components to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from previous response"},"include-deleted":{type:"boolean",description:"Include deregistered components"}}).withExamples(["sazabi components list # List all components","sazabi components list --include-deleted # Include deregistered components"]).build(),get:L("get","Get one component by ID",async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Component ID is required.");return D("Component ID is required.")}await qxA(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<component-id>").withOptions(z).withExamples(["sazabi components get <component-id> # Get one component"]).build(),register:L("register","Register or refresh a component",async(A)=>{let{values:t}=F(A,{...m,name:{type:"string"},description:{type:"string"},origin:{type:"string"}});await dxA({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],name:t.name,description:t.description,origin:t.origin})}).withOptions({...z,name:{type:"string",description:"Component name to register"},description:{type:"string",description:"Optional component description"},origin:{type:"string",description:"Machine provenance: 'code_detected' (inferred from code) or 'log_observed' (inferred from telemetry, the default)"}}).withExamples(['sazabi components register --name "API Gateway" # Register a component','sazabi components register --name "Checkout" --description "Checkout API and workflow" # Register with description','sazabi components register --name "intake-consumer" --origin code_detected # Register a component inferred from repository analysis']).build(),deregister:L("deregister","Deregister a component",async(A)=>{let{values:t,positionals:g}=F(A,{...m,reason:{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Component ID is required.");return D("Component ID is required.")}await pxA(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],reason:t.reason})}).withPositionalArgs("<component-id>").withOptions({...z,reason:{type:"string",description:"Optional deregistration reason"}}).withExamples(["sazabi components deregister <component-id> # Deregister a component",'sazabi components deregister <component-id> --reason "service retired" # Deregister with reason']).build(),rename:L("rename","Rename an active component",async(A)=>{let{values:t,positionals:g}=F(A,{...m,name:{type:"string"},"request-id":{type:"string"},reason:{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Component ID is required.");return D("Component ID is required.")}await A3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],name:t.name,requestId:t["request-id"],reason:t.reason})}).withPositionalArgs("<component-id>").withOptions({...z,name:{type:"string",description:"New component name"},"request-id":{type:"string",description:"Project-scoped UUID idempotency key"},reason:{type:"string",description:"Audit reason for the rename"}}).build(),retire:L("retire","Preview or confirm component retirement",async(A)=>{let{values:t,positionals:g}=F(A,{...mb,"confirm-canonical-group":{type:"boolean"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Component ID is required.");return D("Component ID is required.")}await t3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],confirmPreviewRevision:t["confirm-preview-revision"],requestId:t["request-id"],reason:t.reason,confirmCanonicalGroup:t["confirm-canonical-group"]})}).withPositionalArgs("<component-id>").withOptions({...Wb,"confirm-canonical-group":{type:"boolean",description:"Confirm the complete canonical group"}}).build(),restore:L("restore","Preview or confirm component restoration",async(A)=>{let{values:t,positionals:g}=F(A,{...mb,"retirement-operation-id":{type:"string"},"notification-rule-ids":{type:"string"},"automation-binding-ids":{type:"string"},"relationship-ids":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Component ID is required.");return D("Component ID is required.")}await g3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],confirmPreviewRevision:t["confirm-preview-revision"],requestId:t["request-id"],reason:t.reason,retirementOperationId:t["retirement-operation-id"],notificationRuleIds:t["notification-rule-ids"],automationBindingIds:t["automation-binding-ids"],relationshipIds:t["relationship-ids"]})}).withPositionalArgs("<component-id>").withOptions({...Wb,"retirement-operation-id":{type:"string",description:"Retirement operation ID returned by the preview"},"notification-rule-ids":{type:"string",description:"Comma-separated eligible notification rule IDs"},"automation-binding-ids":{type:"string",description:"Comma-separated eligible automation binding IDs"},"relationship-ids":{type:"string",description:"Comma-separated eligible relationship IDs"}}).build(),merge:L("merge","Preview or confirm present-day component consolidation",async(A)=>{let{values:t}=F(A,{...mb,source:{type:"string"},target:{type:"string"},"policy-dispositions":{type:"string"},"confirm-policy-impact":{type:"boolean"}});await n3A({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],sourceComponentId:t.source,targetComponentId:t.target,confirmPreviewRevision:t["confirm-preview-revision"],requestId:t["request-id"],reason:t.reason,policyDispositions:t["policy-dispositions"],confirmPolicyImpact:t["confirm-policy-impact"]})}).withOptions({...Wb,source:{type:"string",description:"Source component ID"},target:{type:"string",description:"Target component ID"},"policy-dispositions":{type:"string",description:"Exact non-equivalent policy disposition JSON"},"confirm-policy-impact":{type:"boolean",description:"Confirm every previewed policy-scope change"}}).withExamples(["sazabi components merge --source <component-id> --target <component-id> # Preview only"]).build(),relationships:e3A}).withExamples(["sazabi components list # List all components","sazabi components get <component-id> # Get one component",'sazabi components register --name "API Gateway" # Register a component',"sazabi components deregister <component-id> # Deregister a component"]).build();iA();$Q();uA();import{spawn as Q3A}from"node:child_process";var YB=(A)=>{let t=process.platform,g,i;if(t==="darwin")g="open",i=[A];else if(t==="win32")g="cmd",i=["/c","start","",A];else g="xdg-open",i=[A];let n=Q3A(g,i,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()},$B=(A)=>new Promise((t)=>setTimeout(t,A));CA();var rrA={provider:{label:"Provider",type:{kind:"string"}},externalName:{label:"Name",type:{kind:"nullable-string"}},externalLogin:{label:"Login",type:{kind:"nullable-string"}},connectedAt:{label:"Connected",type:{kind:"nullable-date"}},authMode:{label:"Auth mode",type:{kind:"nullable-string"}},needsReconnect:{label:"Needs reconnect",type:{kind:"custom",render:(A)=>A?"yes":"no",serialize:(A)=>Boolean(A)}}},I3A={schema:rrA,columns:["provider","externalName","externalLogin","connectedAt","needsReconnect"],header:"Connected accounts",emptyMessage:"No connected accounts found."},h3A={layout:"field-list",schema:rrA,fields:["provider","externalName","externalLogin","connectedAt","authMode","needsReconnect"],title:"Connected account"},B3A={provider:{label:"Provider",type:{kind:"string"}}},c3A={schema:B3A,columns:["provider"],header:"Connected account providers",emptyMessage:"No providers found."},ga=(A)=>{let t=A.json,g=R({tokenFlag:A.token,jsonMode:t});return{client:f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:t}),json:t}},C3A=3000,r3A={vendor_denied:"The authorization was declined in the provider.",not_authorized:"The browser was not signed in to the Sazabi dashboard as your user. Sign in with the same account and run connect again.",state_expired:"The browser flow took too long and expired. Run connect again."},crA=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return u("Provider is required.");return D("Provider is required. Available: github, google, microsoft, linear, bitbucket, slack")}let{client:o}=ga(t),e=l(await o.connectedAccounts.beginConnect({provider:i}),`Couldn't start the ${i} connect flow`,n);if(!n)JA(`Connect ${i}`),IA("Complete the authorization in a browser where you're signed in to the Sazabi dashboard as the same user."),IA(`Opening ${jA.info(e.url)}`);if(YB(e.url),!n)IA("Waiting for the browser flow to complete...");let I=new Date(e.expiresAt).getTime()+15000;while(Date.now()<I){await $B(C3A);let B=l(await o.connectedAccounts.getConnectAttempt(e.attemptId),"Couldn't poll the connect attempt (try again)",n);if(B.status==="pending")continue;if(B.status==="completed"){if(!n)x(`Connected ${i}.`);if(n)X({status:"completed",provider:i});return}if(B.status==="failed"){let c=B.errorCode??"unknown",C=r3A[c],r=C?`Connect did not complete (${c}). ${C}`:`Connect failed (${c}). Run the command again.`;if(n)return u(r);return D(r)}break}let h="The browser flow didn't complete in time. Run the command again.";if(n)return u(h);return D(h)},a3A=async(A)=>{let{values:t}=F(A,m),{client:g,json:i}=ga(t),{accounts:n}=l(await g.connectedAccounts.list(),"Couldn't list connected accounts (try again)",i);s(I3A,n,{json:i})},E3A=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return u("Provider is required.");return D("Provider is required. Run 'sazabi connected-accounts list' to see connected providers.")}let{client:o}=ga(t);if(l(await o.connectedAccounts.disconnect({provider:i}),"Couldn't disconnect the connected account",n),n){X({success:!0});return}x(`Disconnected ${i}.`)},CrA=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return u("Provider is required.");return D("Provider is required. Run 'sazabi connected-accounts list' to see connected providers.")}let{client:o}=ga(t),{accounts:e}=l(await o.connectedAccounts.list(),"Couldn't list connected accounts (try again)",n),I=e.find((h)=>h.provider===i);if(!I){let h=`No connected account found for provider '${i}'.`;if(n)return u(h);return D(h)}W(h3A,I,{json:n})},y3A=async(A)=>{let{values:t}=F(A,m),{json:g}=ga(t),i=Ry.map((n)=>({provider:n}));s(c3A,i,{json:g})},arA=nA("connected-accounts","Manage personal connected accounts (GitHub, Google, Microsoft, Linear, Bitbucket, Slack)").withSubcommands({connect:L("connect","Connect a personal account via a browser OAuth flow",crA).withPositionalArgs("<provider>").withOptions(z).withExamples(["sazabi connected-accounts connect github # Connect GitHub","sazabi connected-accounts connect google # Connect Google","sazabi connected-accounts connect slack # Connect Slack"]).build(),list:L("list","List connected accounts for the organization",a3A).withOptions(z).withExamples(["sazabi connected-accounts list # List connected accounts","sazabi connected-accounts list --json # Machine-readable output"]).build(),get:L("get","Get one connected account by provider",CrA).withPositionalArgs("<provider>").withOptions(z).withExamples(["sazabi connected-accounts get github # Show GitHub connected account","sazabi connected-accounts get slack --json # Machine-readable output"]).build(),details:L("details","Show details for one connected account",CrA).withPositionalArgs("<provider>").withOptions(z).withExamples(["sazabi connected-accounts details github # Show GitHub connected account detail"]).build(),providers:L("providers","List supported connected account providers",y3A).withOptions(z).withExamples(["sazabi connected-accounts providers # List all providers","sazabi connected-accounts providers --json # Machine-readable output"]).build(),disconnect:L("disconnect","Disconnect a personal connected account",E3A).withPositionalArgs("<provider>").withOptions(z).withExamples(["sazabi connected-accounts disconnect github # Disconnect GitHub"]).build(),"update-credentials":L("update-credentials","Reconnect a provider to refresh its OAuth token",crA).withPositionalArgs("<provider>").withOptions(z).withExamples(["sazabi connected-accounts update-credentials github # Re-run the GitHub OAuth flow","sazabi connected-accounts update-credentials slack # Refresh Slack token"]).build()}).withExamples(["sazabi connected-accounts list # List connected accounts","sazabi connected-accounts get github # Show GitHub account","sazabi connected-accounts providers # List available providers","sazabi connected-accounts connect github # Connect GitHub via browser","sazabi connected-accounts disconnect github # Disconnect GitHub","sazabi connected-accounts update-credentials github # Refresh GitHub token"]).build();iA();uA();CA();var w3A={id:{label:"ID",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},authType:{label:"Auth",type:{kind:"string"}},capabilities:{label:"Capabilities",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"",serialize:(A)=>A??[]}},connectionCount:{label:"Connections",type:{kind:"number"}},browserConnectSupported:{label:"Browser connect",type:{kind:"custom",render:(A)=>A?"yes":"no",serialize:(A)=>Boolean(A)}},credentialFields:{label:"Credential fields",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.map((t)=>t.name).join(", "):"",serialize:(A)=>A??null}}},D3A={schema:w3A,columns:["id","name","authType","capabilities","connectionCount"],jsonFields:["id","name","authType","capabilities","connectionCount","browserConnectSupported","credentialFields"],header:"Integration providers",emptyMessage:"No integration providers found."},wrA={id:{label:"ID",type:{kind:"string"}},provider:{label:"Provider",type:{kind:"string"}},displayName:{label:"Name",type:{kind:"nullable-string"}},status:{label:"Status",type:{kind:"string"}},healthStatus:{label:"Health",type:{kind:"string"}},metadata:{label:"Metadata",type:{kind:"custom",render:(A)=>A==null?"":JSON.stringify(A),serialize:(A)=>A??null}},healthMessage:{label:"Health detail",type:{kind:"nullable-string"}},healthCheckedAt:{label:"Health checked",type:{kind:"nullable-date"}},healthConsecutiveFailures:{label:"Health failures",type:{kind:"number"}},connectedBy:{label:"Connected by",type:{kind:"nullable-string"}},createdAt:{label:"Created",type:{kind:"date"}},updatedAt:{label:"Updated",type:{kind:"date"}}},u3A={schema:wrA,columns:["id","provider","displayName","status","healthStatus"],header:"Integration connections",emptyMessage:"No integration connections found."},jb={layout:"field-list",schema:wrA,fields:["id","provider","displayName","status","metadata","healthStatus","healthMessage","healthCheckedAt","healthConsecutiveFailures","connectedBy","createdAt","updatedAt"],title:"Integration connection"},GB=(A)=>{let t=A.json,g=R({tokenFlag:A.token,jsonMode:t});return{client:f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:t}),json:t}},b3A=async(A)=>{let{values:t}=F(A,m),{client:g,json:i}=GB(t),{providers:n}=l(await g.integrations.listProviders(),"Couldn't list integration providers (try again)",i),o=[...n].sort((e,I)=>e.name.localeCompare(I.name));s(D3A,o,{json:i})},l3A=async(A)=>{let{values:t}=F(A,{...m,provider:{type:"string"}}),{client:g,json:i}=GB(t),{connections:n}=l(await g.integrations.listConnections({provider:t.provider}),"Couldn't list integration connections (check your organization access and try again)",i);s(u3A,n,{json:i})},ErA=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Connection ID is required.");return D("Connection ID is required.")}let{client:n,json:o}=GB(t),{connection:e}=l(await n.integrations.getConnection(i),"Couldn't get integration connection (run 'sazabi integrations connections list' to see connection IDs)",o);W(jb,e,{json:o})},N3A=3000,yrA={installation_requested:"The install needs approval from a GitHub organization admin. The connection will appear once they approve — no need to rerun connect.",vendor_denied:"The authorization was declined in the provider.",not_authorized:"The browser wasn't signed in to the Sazabi dashboard as your user. Sign in with the same account and run connect again.",state_expired:"The browser flow took too long and expired. Run connect again."},U3A=(A)=>A.map((t)=>` ${t.name}${t.required?"":" (optional)"} — ${t.label}`).join(`
8749
+ `.trim();var OxA=async(A)=>{let{values:t}=F(A,{json:{type:"boolean"}}),g=orA();if(t.json){X({shell:"zsh",script:g});return}console.log(g)},zxA=async(A)=>{let{values:t}=F(A,{json:{type:"boolean"}}),g=erA();if(t.json){X({shell:"bash",script:g});return}console.log(g)},QrA=nA("completions","Shell completion scripts").withSubcommands({zsh:L("zsh","Output zsh completion script",OxA).withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(['eval "$(sazabi completions zsh)" # Add to .zshrc']).build(),bash:L("bash","Output bash completion script",zxA).withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(['eval "$(sazabi completions bash)" # Add to .bashrc']).build()}).withExamples(['eval "$(sazabi completions zsh)" # Enable zsh completions','eval "$(sazabi completions bash)" # Enable bash completions']).build();iA();uA();CA();var hrA={id:{label:"ID",type:{kind:"string"}},projectId:{label:"Project",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},currentStatus:{label:"Status",type:{kind:"string"}},description:{label:"Description",type:{kind:"nullable-string"}},origin:{label:"Origin",type:{kind:"string"}},lifecycle:{label:"Lifecycle",type:{kind:"string"}},observationState:{label:"Observation",type:{kind:"string"}},registryRevision:{label:"Revision",type:{kind:"number"}},canonicalComponentId:{label:"Canonical component",type:{kind:"id"}},mergedIntoComponentId:{label:"Merged into",type:{kind:"nullable-string"}},firstSeenAt:{label:"Created at",type:{kind:"date"}},lastSeenAt:{label:"Last seen",type:{kind:"date"}},deletedAt:{label:"Deleted at",type:{kind:"nullable-date"}},retiredAt:{label:"Retired at",type:{kind:"nullable-date"}},retirementReason:{label:"Retirement reason",type:{kind:"nullable-string"}},legacyStateUnknown:{label:"Legacy inactive",type:{kind:"boolean"}}},mxA={schema:hrA,columns:["id","name","lifecycle","observationState","currentStatus"],jsonFields:["id","projectId","name","currentStatus","description","origin","lifecycle","observationState","registryRevision","canonicalComponentId","mergedIntoComponentId","firstSeenAt","lastSeenAt","deletedAt","retiredAt","retirementReason","legacyStateUnknown"],emptyMessage:"No components found. Register one with 'sazabi components register --name <name>'."},Bv={layout:"field-list",schema:hrA,fields:["id","projectId","name","currentStatus","description","origin","lifecycle","observationState","registryRevision","canonicalComponentId","mergedIntoComponentId","firstSeenAt","lastSeenAt","deletedAt","retiredAt","retirementReason","legacyStateUnknown"],title:"Component"},WxA={status:{label:"Status",type:{kind:"string"}},componentId:{label:"Component ID",type:{kind:"id"}},sourceType:{label:"Source type",type:{kind:"string"}},withdrawn:{label:"Withdrawn",type:{kind:"boolean"}}},ZxA={layout:"field-list",schema:WxA,fields:["status","componentId","sourceType","withdrawn"],title:"Component observation"},VxA=(A)=>{let t=A,g=Object.values(t.counts).reduce((i,n)=>i+n,0);return`${t.canonicalComponentName} (${t.canonicalComponentId}); ${t.affectedComponentIds.length} component(s), ${g} dependent(s); no changes applied`},jxA={status:{label:"Status",type:{kind:"string"}},preview:{label:"Retirement preview",type:{kind:"custom",render:VxA,serialize:(A)=>A}}},HxA={layout:"field-list",schema:jxA,fields:["status","preview"],title:"Retirement confirmation required"},ta=(A,t,g)=>{if(A===void 0)return;try{let i=JSON.parse(A);if(!i||typeof i!=="object"||Array.isArray(i))throw Error("must be a JSON object");return i}catch(i){let n=`${t} must be valid JSON: ${i instanceof Error?i.message:String(i)}`;if(g)return u(n);return D(n)}},hv=(A)=>A?A.split(",").map((t)=>t.trim()).filter(Boolean):[],cv={kind:"custom",render:(A)=>JSON.stringify(A,null,2),serialize:(A)=>A},XxA={preview:{label:"Preview",type:cv}},KxA={layout:"field-list",schema:XxA,fields:["preview"],title:"Component operation preview"},_xA={result:{label:"Result",type:cv}},sxA={layout:"field-list",schema:_xA,fields:["result"],title:"Component operation result"},Zb=(A,t)=>W(KxA,A,{json:t}),Vb=(A,t)=>W(sxA,A,{json:t}),xxA=async(A)=>{let t=R({tokenFlag:A.token,jsonMode:A.json}),g=f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=l(await g.components.list({limit:A.limit,cursor:A.cursor,includeDeleted:A.includeDeleted}),"Couldn't list components (check the active project and try again)",A.json);s(mxA,i.components,{json:A.json,nextCursor:i.nextCursor})},qxA=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.components.get(A),"Couldn't get component (run 'sazabi components list' to see component IDs)",t.json);W(Bv,n.component,{json:t.json})},dxA=async(A)=>{let t=A.name?.trim(),g=A.description?.trim(),i=A.origin?.trim();if(!t){if(A.json)return u("Name is required.");return D("Name is required.")}if(A.description!==void 0&&!g){if(A.json)return u("Description cannot be empty.");return D("Description cannot be empty.")}if(i!==void 0&&i!=="code_detected"&&i!=="log_observed"){if(A.json)return u("Invalid origin. Use 'code_detected' (inferred from code) or 'log_observed' (inferred from telemetry).");return D("Invalid origin. Use 'code_detected' (inferred from code) or 'log_observed' (inferred from telemetry).")}let n=R({tokenFlag:A.token,jsonMode:A.json}),o=f({token:n.token,organizationId:n.organizationId,projectId:n.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),e=l(await o.components.register({name:t,...g?{description:g}:{},...i?{origin:i}:{}}),"Failed to register component",A.json);W(Bv,e.component,{json:A.json})},pxA=async(A,t)=>{let g=t.reason?.trim();if(t.reason!==void 0&&!g){if(t.json)return u("Reason cannot be empty.");return D("Reason cannot be empty.")}let i=R({tokenFlag:t.token,jsonMode:t.json}),n=f({token:i.token,organizationId:i.organizationId,projectId:i.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),o=l(await n.components.deregister(A,g),"Failed to deregister component",t.json);if(o.status==="observation_withdrawn"){W(ZxA,o,{json:t.json});return}W(HxA,o,{json:t.json})},kB=(A)=>{let t=R({tokenFlag:A.token,jsonMode:A.json});return f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json})},A3A=async(A,t)=>{let g=t.name?.trim(),i=t.reason?.trim();if(!g){if(t.json)return u("Name is required.");return D("Name is required.")}if(!t.requestId){if(t.json)return u("Request ID is required.");return D("Request ID is required.")}if(!i){if(t.json)return u("Reason is required.");return D("Reason is required.")}let n=kB(t),o=l(await n.components.rename({componentId:A,name:g,requestId:t.requestId,reason:i}),"Failed to rename component",t.json);W(Bv,o.component,{json:t.json})},t3A=async(A,t)=>{let g=kB(t),i=ta(t.confirmPreviewRevision,"Confirm preview revision",t.json);if(!i){let e=l(await g.components.retirementPreview({componentId:A}),"Failed to preview component retirement",t.json);Zb(e,t.json);return}let n=t.reason?.trim();if(!t.requestId||!n){if(t.json)return u("Commit requires --request-id and --reason with --confirm-preview-revision.");return D("Commit requires --request-id and --reason with --confirm-preview-revision.")}let o=l(await g.components.retire({componentId:A,requestId:t.requestId,reason:n,componentRevisions:i,confirmCanonicalGroup:t.confirmCanonicalGroup??!1}),"Failed to retire component; refresh the preview if it changed",t.json);Vb(o,t.json)},g3A=async(A,t)=>{let g=kB(t),i=ta(t.confirmPreviewRevision,"Confirm preview revision",t.json);if(!i){let e=l(await g.components.restorationPreview({componentId:A,...t.retirementOperationId?{retirementOperationId:t.retirementOperationId}:{}}),"Failed to preview component restoration",t.json);Zb(e,t.json);return}let n=t.reason?.trim();if(!t.requestId||!t.retirementOperationId||!n){if(t.json)return u("Commit requires --request-id, --retirement-operation-id, and --reason with --confirm-preview-revision.");return D("Commit requires --request-id, --retirement-operation-id, and --reason with --confirm-preview-revision.")}let o=l(await g.components.restore({componentId:A,retirementOperationId:t.retirementOperationId,requestId:t.requestId,reason:n,componentRevisions:i,selections:{notificationRuleIds:hv(t.notificationRuleIds),automationBindingIds:hv(t.automationBindingIds),recommendationScopeIds:[],relationshipIds:hv(t.relationshipIds)}}),"Failed to restore component; refresh the preview if it changed",t.json);Vb(o,t.json)},n3A=async(A)=>{if(!A.sourceComponentId||!A.targetComponentId){if(A.json)return u("Source and target component IDs are required.");return D("Source and target component IDs are required.")}let t=kB(A),g={sourceComponentId:A.sourceComponentId,targetComponentId:A.targetComponentId},i=ta(A.confirmPreviewRevision,"Confirm preview revision",A.json);if(!i){let I=l(await t.components.mergePreview(g),"Failed to preview component consolidation",A.json);Zb(I,A.json);return}let n=A.reason?.trim(),o=ta(A.policyDispositions,"Policy dispositions",A.json);if(!A.requestId||!n||!o){if(A.json)return u("Commit requires --request-id, --reason, and --policy-dispositions with --confirm-preview-revision.");return D("Commit requires --request-id, --reason, and --policy-dispositions with --confirm-preview-revision.")}let e=l(await t.components.merge({...g,requestId:A.requestId,reason:n,componentRevisions:i,policyDispositions:o,confirmPolicyImpact:A.confirmPolicyImpact??!1}),"Failed to consolidate component; refresh the preview if it changed",A.json);Vb(e,A.json)},i3A=async(A)=>{let t=kB(A),g=l(await t.components.relationships.list({includeHistorical:A.includeHistorical}),"Failed to list component relationships",A.json);W({layout:"field-list",schema:{relationships:{label:"Relationships",type:cv}},fields:["relationships"],title:"Component relationships"},g,{json:A.json})},o3A=async(A,t)=>{if(!t.sourceComponentId||!t.targetComponentId||t.relationshipType!=="part_of"&&t.relationshipType!=="depends_on"){if(t.json)return u("Source, target, and relationship type (part_of or depends_on) are required.");return D("Source, target, and relationship type (part_of or depends_on) are required.")}let g=kB(t),i={action:A,sourceComponentId:t.sourceComponentId,targetComponentId:t.targetComponentId,relationshipType:t.relationshipType},n=ta(t.confirmPreviewRevision,"Confirm preview revision",t.json);if(!n){let h=l(await g.components.relationships.preview(i),"Failed to preview component relationship",t.json);Zb(h,t.json);return}let o=t.reason?.trim();if(!t.requestId||!o){if(t.json)return u("Commit requires --request-id and --reason with --confirm-preview-revision.");return D("Commit requires --request-id and --reason with --confirm-preview-revision.")}let e={sourceComponentId:i.sourceComponentId,targetComponentId:i.targetComponentId,relationshipType:i.relationshipType,requestId:t.requestId,reason:o,componentRevisions:n,confirmPolicyImpact:t.confirmPolicyImpact??!1},I=l(A==="add"?await g.components.relationships.add(e):await g.components.relationships.remove(e),`Failed to ${A} component relationship; refresh the preview if it changed`,t.json);Vb(I,t.json)},mb={...m,"confirm-preview-revision":{type:"string"},"request-id":{type:"string"},reason:{type:"string"}},Wb={...z,"confirm-preview-revision":{type:"string",description:"Exact componentRevisions JSON from the preview; omit to preview only"},"request-id":{type:"string",description:"Project-scoped UUID idempotency key required for commit"},reason:{type:"string",description:"Audit reason required for commit"}},IrA=(A)=>L(A,`${A==="add"?"Add":"End"} a component relationship`,async(t)=>{let{values:g}=F(t,{...mb,source:{type:"string"},target:{type:"string"},type:{type:"string"},"confirm-policy-impact":{type:"boolean"}});await o3A(A,{token:g.token,json:g.json,apiBaseUrl:g["api-base-url"],sourceComponentId:g.source,targetComponentId:g.target,relationshipType:g.type,confirmPreviewRevision:g["confirm-preview-revision"],requestId:g["request-id"],reason:g.reason,confirmPolicyImpact:g["confirm-policy-impact"]})}).withOptions({...Wb,source:{type:"string",description:"Source component ID"},target:{type:"string",description:"Target component ID"},type:{type:"string",description:"Relationship type: part_of or depends_on"},"confirm-policy-impact":{type:"boolean",description:"Confirm the policy-scope delta shown by the preview"}}).withExamples([`sazabi components relationships ${A} --source <component-id> --target <component-id> --type part_of # Preview a parent-child topology change`]).build(),e3A=nA("relationships","Inspect and edit component topology").withSubcommands({list:L("list","List component relationships",async(A)=>{let{values:t}=F(A,{...m,"include-historical":{type:"boolean"}});await i3A({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],includeHistorical:t["include-historical"]})}).withOptions({...z,"include-historical":{type:"boolean",description:"Include historically ended relationships"}}).build(),add:IrA("add"),remove:IrA("remove")}).build(),BrA=nA("components","Manage status page components").withSubcommands({list:L("list","List components in the active project",async(A)=>{let{values:t}=F(A,{...m,limit:{type:"string"},cursor:{type:"string"},"include-deleted":{type:"boolean"}});await xxA({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],limit:t.limit?Number(t.limit):void 0,cursor:t.cursor,includeDeleted:t["include-deleted"]})}).withOptions({...z,limit:{type:"string",description:"Maximum number of components to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from previous response"},"include-deleted":{type:"boolean",description:"Include deregistered components"}}).withExamples(["sazabi components list # List all components","sazabi components list --include-deleted # Include deregistered components"]).build(),get:L("get","Get one component by ID",async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Component ID is required.");return D("Component ID is required.")}await qxA(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<component-id>").withOptions(z).withExamples(["sazabi components get <component-id> # Get one component"]).build(),register:L("register","Register or refresh a component",async(A)=>{let{values:t}=F(A,{...m,name:{type:"string"},description:{type:"string"},origin:{type:"string"}});await dxA({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],name:t.name,description:t.description,origin:t.origin})}).withOptions({...z,name:{type:"string",description:"Component name to register"},description:{type:"string",description:"Optional component description"},origin:{type:"string",description:"Machine provenance: 'code_detected' (inferred from code) or 'log_observed' (inferred from telemetry, the default)"}}).withExamples(['sazabi components register --name "API Gateway" # Register a component','sazabi components register --name "Checkout" --description "Checkout API and workflow" # Register with description','sazabi components register --name "intake-consumer" --origin code_detected # Register a component inferred from repository analysis']).build(),deregister:L("deregister","Deregister a component",async(A)=>{let{values:t,positionals:g}=F(A,{...m,reason:{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Component ID is required.");return D("Component ID is required.")}await pxA(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],reason:t.reason})}).withPositionalArgs("<component-id>").withOptions({...z,reason:{type:"string",description:"Optional deregistration reason"}}).withExamples(["sazabi components deregister <component-id> # Deregister a component",'sazabi components deregister <component-id> --reason "service retired" # Deregister with reason']).build(),rename:L("rename","Rename an active component",async(A)=>{let{values:t,positionals:g}=F(A,{...m,name:{type:"string"},"request-id":{type:"string"},reason:{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Component ID is required.");return D("Component ID is required.")}await A3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],name:t.name,requestId:t["request-id"],reason:t.reason})}).withPositionalArgs("<component-id>").withOptions({...z,name:{type:"string",description:"New component name"},"request-id":{type:"string",description:"Project-scoped UUID idempotency key"},reason:{type:"string",description:"Audit reason for the rename"}}).build(),retire:L("retire","Preview or confirm component retirement",async(A)=>{let{values:t,positionals:g}=F(A,{...mb,"confirm-canonical-group":{type:"boolean"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Component ID is required.");return D("Component ID is required.")}await t3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],confirmPreviewRevision:t["confirm-preview-revision"],requestId:t["request-id"],reason:t.reason,confirmCanonicalGroup:t["confirm-canonical-group"]})}).withPositionalArgs("<component-id>").withOptions({...Wb,"confirm-canonical-group":{type:"boolean",description:"Confirm the complete canonical group"}}).build(),restore:L("restore","Preview or confirm component restoration",async(A)=>{let{values:t,positionals:g}=F(A,{...mb,"retirement-operation-id":{type:"string"},"notification-rule-ids":{type:"string"},"automation-binding-ids":{type:"string"},"relationship-ids":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Component ID is required.");return D("Component ID is required.")}await g3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],confirmPreviewRevision:t["confirm-preview-revision"],requestId:t["request-id"],reason:t.reason,retirementOperationId:t["retirement-operation-id"],notificationRuleIds:t["notification-rule-ids"],automationBindingIds:t["automation-binding-ids"],relationshipIds:t["relationship-ids"]})}).withPositionalArgs("<component-id>").withOptions({...Wb,"retirement-operation-id":{type:"string",description:"Retirement operation ID returned by the preview"},"notification-rule-ids":{type:"string",description:"Comma-separated eligible notification rule IDs"},"automation-binding-ids":{type:"string",description:"Comma-separated eligible automation binding IDs"},"relationship-ids":{type:"string",description:"Comma-separated eligible relationship IDs"}}).build(),merge:L("merge","Preview or confirm present-day component consolidation",async(A)=>{let{values:t}=F(A,{...mb,source:{type:"string"},target:{type:"string"},"policy-dispositions":{type:"string"},"confirm-policy-impact":{type:"boolean"}});await n3A({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],sourceComponentId:t.source,targetComponentId:t.target,confirmPreviewRevision:t["confirm-preview-revision"],requestId:t["request-id"],reason:t.reason,policyDispositions:t["policy-dispositions"],confirmPolicyImpact:t["confirm-policy-impact"]})}).withOptions({...Wb,source:{type:"string",description:"Source component ID"},target:{type:"string",description:"Target component ID"},"policy-dispositions":{type:"string",description:"Exact non-equivalent policy disposition JSON"},"confirm-policy-impact":{type:"boolean",description:"Confirm every previewed policy-scope change"}}).withExamples(["sazabi components merge --source <component-id> --target <component-id> # Preview only"]).build(),relationships:e3A}).withExamples(["sazabi components list # List all components","sazabi components get <component-id> # Get one component",'sazabi components register --name "API Gateway" # Register a component',"sazabi components deregister <component-id> # Deregister a component"]).build();iA();$Q();uA();import{spawn as Q3A}from"node:child_process";var YB=(A)=>{let t=process.platform,g,i;if(t==="darwin")g="open",i=[A];else if(t==="win32")g="cmd",i=["/c","start","",A];else g="xdg-open",i=[A];let n=Q3A(g,i,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()},$B=(A)=>new Promise((t)=>setTimeout(t,A));CA();var rrA={provider:{label:"Provider",type:{kind:"string"}},externalName:{label:"Name",type:{kind:"nullable-string"}},externalLogin:{label:"Login",type:{kind:"nullable-string"}},connectedAt:{label:"Connected",type:{kind:"nullable-date"}},authMode:{label:"Auth mode",type:{kind:"nullable-string"}},needsReconnect:{label:"Needs reconnect",type:{kind:"custom",render:(A)=>A?"yes":"no",serialize:(A)=>Boolean(A)}}},I3A={schema:rrA,columns:["provider","externalName","externalLogin","connectedAt","needsReconnect"],header:"Connected accounts",emptyMessage:"No connected accounts found."},h3A={layout:"field-list",schema:rrA,fields:["provider","externalName","externalLogin","connectedAt","authMode","needsReconnect"],title:"Connected account"},B3A={provider:{label:"Provider",type:{kind:"string"}}},c3A={schema:B3A,columns:["provider"],header:"Connected account providers",emptyMessage:"No providers found."},ga=(A)=>{let t=A.json,g=R({tokenFlag:A.token,jsonMode:t});return{client:f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:t}),json:t}},C3A=3000,r3A={vendor_denied:"The authorization was declined in the provider.",not_authorized:"The browser was not signed in to the Sazabi dashboard as your user. Sign in with the same account and run connect again.",state_expired:"The browser flow took too long and expired. Run connect again."},crA=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return u("Provider is required.");return D("Provider is required. Available: github, google, microsoft, linear, bitbucket, slack")}let{client:o}=ga(t),e=l(await o.connectedAccounts.beginConnect({provider:i}),`Couldn't start the ${i} connect flow`,n);if(!n)JA(`Connect ${i}`),IA("Complete the authorization in a browser where you're signed in to the Sazabi dashboard as the same user."),IA(`Opening ${jA.info(e.url)}`);if(YB(e.url),!n)IA("Waiting for the browser flow to complete...");let I=new Date(e.expiresAt).getTime()+15000;while(Date.now()<I){await $B(C3A);let B=l(await o.connectedAccounts.getConnectAttempt(e.attemptId),"Couldn't poll the connect attempt (try again)",n);if(B.status==="pending")continue;if(B.status==="completed"){if(!n)x(`Connected ${i}.`);if(n)X({status:"completed",provider:i});return}if(B.status==="failed"){let c=B.errorCode??"unknown",C=r3A[c],r=C?`Connect did not complete (${c}). ${C}`:`Connect failed (${c}). Run the command again.`;if(n)return u(r);return D(r)}break}let h="The browser flow didn't complete in time. Run the command again.";if(n)return u(h);return D(h)},a3A=async(A)=>{let{values:t}=F(A,m),{client:g,json:i}=ga(t),{accounts:n}=l(await g.connectedAccounts.list(),"Couldn't list connected accounts (try again)",i);s(I3A,n,{json:i})},E3A=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return u("Provider is required.");return D("Provider is required. Run 'sazabi connected-accounts list' to see connected providers.")}let{client:o}=ga(t);if(l(await o.connectedAccounts.disconnect({provider:i}),"Couldn't disconnect the connected account",n),n){X({success:!0});return}x(`Disconnected ${i}.`)},CrA=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return u("Provider is required.");return D("Provider is required. Run 'sazabi connected-accounts list' to see connected providers.")}let{client:o}=ga(t),{accounts:e}=l(await o.connectedAccounts.list(),"Couldn't list connected accounts (try again)",n),I=e.find((h)=>h.provider===i);if(!I){let h=`No connected account found for provider '${i}'.`;if(n)return u(h);return D(h)}W(h3A,I,{json:n})},y3A=async(A)=>{let{values:t}=F(A,m),{json:g}=ga(t),i=Ry.map((n)=>({provider:n}));s(c3A,i,{json:g})},arA=nA("connected-accounts","Manage personal connected accounts (GitHub, Google, Microsoft, Linear, Bitbucket, Slack)").withSubcommands({connect:L("connect","Connect a personal account via a browser OAuth flow",crA).withPositionalArgs("<provider>").withOptions(z).withExamples(["sazabi connected-accounts connect github # Connect GitHub","sazabi connected-accounts connect google # Connect Google","sazabi connected-accounts connect slack # Connect Slack"]).build(),list:L("list","List connected accounts for the organization",a3A).withOptions(z).withExamples(["sazabi connected-accounts list # List connected accounts","sazabi connected-accounts list --json # Machine-readable output"]).build(),get:L("get","Get one connected account by provider",CrA).withPositionalArgs("<provider>").withOptions(z).withExamples(["sazabi connected-accounts get github # Show GitHub connected account","sazabi connected-accounts get slack --json # Machine-readable output"]).build(),details:L("details","Show details for one connected account",CrA).withPositionalArgs("<provider>").withOptions(z).withExamples(["sazabi connected-accounts details github # Show GitHub connected account detail"]).build(),providers:L("providers","List supported connected account providers",y3A).withOptions(z).withExamples(["sazabi connected-accounts providers # List all providers","sazabi connected-accounts providers --json # Machine-readable output"]).build(),disconnect:L("disconnect","Disconnect a personal connected account",E3A).withPositionalArgs("<provider>").withOptions(z).withExamples(["sazabi connected-accounts disconnect github # Disconnect GitHub"]).build(),"update-credentials":L("update-credentials","Reconnect a provider to refresh its OAuth token",crA).withPositionalArgs("<provider>").withOptions(z).withExamples(["sazabi connected-accounts update-credentials github # Re-run the GitHub OAuth flow","sazabi connected-accounts update-credentials slack # Refresh Slack token"]).build()}).withExamples(["sazabi connected-accounts list # List connected accounts","sazabi connected-accounts get github # Show GitHub account","sazabi connected-accounts providers # List available providers","sazabi connected-accounts connect github # Connect GitHub via browser","sazabi connected-accounts disconnect github # Disconnect GitHub","sazabi connected-accounts update-credentials github # Refresh GitHub token"]).build();iA();uA();CA();var w3A={id:{label:"ID",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},authType:{label:"Auth",type:{kind:"string"}},capabilities:{label:"Capabilities",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"",serialize:(A)=>A??[]}},connectionCount:{label:"Connections",type:{kind:"number"}},browserConnectSupported:{label:"Browser connect",type:{kind:"custom",render:(A)=>A?"yes":"no",serialize:(A)=>Boolean(A)}},credentialFields:{label:"Credential fields",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.map((t)=>t.name).join(", "):"",serialize:(A)=>A??null}}},D3A={schema:w3A,columns:["id","name","authType","capabilities","connectionCount"],jsonFields:["id","name","authType","capabilities","connectionCount","browserConnectSupported","credentialFields"],header:"Integration providers",emptyMessage:"No integration providers found."},wrA={id:{label:"ID",type:{kind:"string"}},provider:{label:"Provider",type:{kind:"string"}},displayName:{label:"Name",type:{kind:"nullable-string"}},status:{label:"Status",type:{kind:"string"}},healthStatus:{label:"Health",type:{kind:"string"}},metadata:{label:"Metadata",type:{kind:"custom",render:(A)=>A==null?"":JSON.stringify(A),serialize:(A)=>A??null}},healthMessage:{label:"Health detail",type:{kind:"nullable-string"}},healthCheckedAt:{label:"Health checked",type:{kind:"nullable-date"}},healthConsecutiveFailures:{label:"Health failures",type:{kind:"number"}},connectedBy:{label:"Connected by",type:{kind:"nullable-string"}},createdAt:{label:"Created",type:{kind:"date"}},updatedAt:{label:"Updated",type:{kind:"date"}}},u3A={schema:wrA,columns:["id","provider","displayName","status","healthStatus"],header:"Integration connections",emptyMessage:"No integration connections found."},jb={layout:"field-list",schema:wrA,fields:["id","provider","displayName","status","metadata","healthStatus","healthMessage","healthCheckedAt","healthConsecutiveFailures","connectedBy","createdAt","updatedAt"],title:"Integration connection"},GB=(A)=>{let t=A.json,g=R({tokenFlag:A.token,jsonMode:t});return{client:f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:t}),json:t}},b3A=async(A)=>{let{values:t}=F(A,m),{client:g,json:i}=GB(t),{providers:n}=l(await g.integrations.listProviders(),"Couldn't list integration providers (try again)",i),o=[...n].sort((e,I)=>e.name.localeCompare(I.name));s(D3A,o,{json:i})},l3A=async(A)=>{let{values:t}=F(A,{...m,provider:{type:"string"}}),{client:g,json:i}=GB(t),{connections:n}=l(await g.integrations.listConnections({provider:t.provider}),"Couldn't list integration connections (check your organization access and try again)",i);s(u3A,n,{json:i})},ErA=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Connection ID is required.");return D("Connection ID is required.")}let{client:n,json:o}=GB(t),{connection:e}=l(await n.integrations.getConnection(i),"Couldn't get integration connection (run 'sazabi integrations list' to see connection IDs)",o);W(jb,e,{json:o})},N3A=3000,yrA={installation_requested:"The install needs approval from a GitHub organization admin. The connection will appear once they approve — no need to rerun connect.",vendor_denied:"The authorization was declined in the provider.",not_authorized:"The browser wasn't signed in to the Sazabi dashboard as your user. Sign in with the same account and run connect again.",state_expired:"The browser flow took too long and expired. Run connect again."},U3A=(A)=>A.map((t)=>` ${t.name}${t.required?"":" (optional)"} — ${t.label}`).join(`
8750
8750
  `),DrA=(A,t,g,i)=>{let n=g.length?`
8751
8751
  ${t} credential fields:
8752
- ${U3A(g)}`:"";if(!A){let o=`--credentials is required for ${t} (JSON object).${n}`;if(i)u(o);else D(o);return}try{let o=JSON.parse(A);if(typeof o!=="object"||o===null||Array.isArray(o))throw Error("not an object");return o}catch{let o=`--credentials must be a JSON object, e.g. '{"apiToken":"..."}'.${n}`;if(i)u(o);else D(o);return}},L3A=async(A)=>{let{values:t,positionals:g}=F(A,{...m,credentials:{type:"string"},"display-name":{type:"string"},project:{type:"string"}},{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return u("Provider is required.");return D("Provider is required. Run 'sazabi integrations providers' to see options.")}let{client:o}=GB(t),{providers:e}=l(await o.integrations.listProviders(),"Couldn't load the integration provider catalog (try again)",n),I=e.find((r)=>r.id===i);if(!I){let r=e.map((y)=>y.id).join(", "),a=`Unknown integration provider "${i}". Available: ${r}`;if(n)return u(a);return D(a)}let h=t["display-name"];if(I.authType==="api_key"){let r=DrA(t.credentials,I.name,I.credentialFields??[],n);if(!r)return;let{connection:a}=l(await o.integrations.createConnection({provider:i,displayName:h,credentials:r}),`Couldn't connect ${I.name} (check the credentials and try again)`,n);if(!n)x(`Connected ${I.name}.`);W(jb,a,{json:n});return}if(!I.browserConnectSupported){let r=`${I.name} can't be connected from the CLI yet. Connect it from the dashboard integration settings.`;if(n)return u(r);return D(r)}if(t.credentials){let r=`${I.name} connects through a browser flow — --credentials does not apply.`;if(n)return u(r);return D(r)}let B=l(await o.integrations.beginConnect({provider:i,displayName:h,projectId:t.project}),`Couldn't start the ${I.name} connect flow`,n);if(!n)JA(`Connect ${I.name}`),IA("Complete the authorization in a browser where you're signed in to the Sazabi dashboard as the same user."),IA(`Opening ${jA.info(B.url)}`);if(YB(B.url),!n)IA("Waiting for the browser flow to complete...");let c=new Date(B.expiresAt).getTime()+15000;while(Date.now()<c){await $B(N3A);let r=l(await o.integrations.getConnectAttempt(B.attemptId),"Couldn't poll the connect attempt (try again)",n);if(r.status==="pending")continue;if(r.status==="completed"&&r.connection){if(!n)x(`Connected ${I.name}.`);W(jb,r.connection,{json:n});return}if(r.status==="failed"){let a=r.errorCode??"unknown",y=yrA[a],w=y?`Connect did not complete (${a}). ${y}`:`Connect failed (${a}). Run the command again.`;if(n)return u(w);return D(w)}if(r.status==="not_connected"){let a=r.errorCode??void 0,w=(a?yrA[a]:void 0)??"Not connected yet — the flow finished but the connection isn't live (it may be awaiting approval). It'll appear once approved.";if(n){X({status:"not_connected",...a?{reason:a}:{},message:w});return}IA(w);return}break}let C="The browser flow didn't complete in time. Run the command again.";if(n)return u(C);return D(C)},S3A=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return u("Connection ID is required.");return D("Connection ID is required. Run 'sazabi integrations connections list' to see connection IDs.")}let{client:o}=GB(t);if(l(await o.integrations.disconnectConnection(i),"Couldn't disconnect the integration connection",n),n){X({success:!0});return}x("Integration connection disconnected.")},F3A=async(A)=>{let{values:t,positionals:g}=F(A,{...m,credentials:{type:"string"}},{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return u("Connection ID is required.");return D("Connection ID is required. Run 'sazabi integrations connections list' to see connection IDs.")}let o=DrA(t.credentials,"this connection",[],n);if(!o)return;let{client:e}=GB(t),{connection:I}=l(await e.integrations.updateConnectionCredentials({connectionId:i,credentials:o}),"Couldn't update the connection credentials (check the values and try again)",n);if(!n)x("Connection credentials updated.");W(jb,I,{json:n})},urA=nA("integrations","Connect and inspect integrations").withSubcommands({providers:L("providers","List supported integration providers",b3A).withOptions(z).withExamples(["sazabi integrations providers # List providers and connection counts","sazabi integrations providers --json # Machine-readable output"]).build(),connect:L("connect","Connect an integration (API-key credentials or a browser flow)",L3A).withPositionalArgs("<provider>").withOptions({...z,credentials:{type:"string",description:'Vendor credentials as JSON for api_key providers, e.g. \'{"apiToken":"..."}\' (see credentialFields in `integrations providers --json`)'},"display-name":{type:"string",description:"Optional display name for the connection"},project:{type:"string",description:"Project the completed connection defaults its routing to (browser flows)"}}).withExamples([`sazabi integrations connect pagerduty --credentials '{"apiToken":"..."}' # API-key connect`,"sazabi integrations connect jira # Browser OAuth connect","sazabi integrations connect github # GitHub App install"]).build(),disconnect:L("disconnect","Disconnect an integration connection",S3A).withPositionalArgs("<connection-id>").withOptions(z).withExamples(["sazabi integrations disconnect <connection-id> # Soft-delete the connection"]).build(),"update-credentials":L("update-credentials","Replace an api_key connection's credentials (reconnect path)",F3A).withPositionalArgs("<connection-id>").withOptions({...z,credentials:{type:"string",description:"Replacement vendor credentials as JSON"}}).withExamples([`sazabi integrations update-credentials <connection-id> --credentials '{"apiToken":"..."}' # Replace stored credentials`]).build(),connections:L("connections","Inspect integration connections").withSubcommands({list:L("list","List integration connections for the organization",l3A).withOptions({...z,provider:{type:"string",description:"Filter by provider (e.g. slack, github, pagerduty)"}}).withExamples(["sazabi integrations connections list # All connections","sazabi integrations connections list --provider slack # Filter by provider"]).build(),get:L("get","Get one integration connection by ID",ErA).withPositionalArgs("<connection-id>").withOptions(z).withExamples(["sazabi integrations connections get <connection-id> # Connection detail"]).build(),details:L("details","Show details for one integration connection",ErA).withPositionalArgs("<connection-id>").withOptions(z).withExamples(["sazabi integrations connections details <connection-id> # Connection detail"]).build()}).withExamples(["sazabi integrations connections list # List connections","sazabi integrations connections get <connection-id> # Connection detail","sazabi integrations connections details <connection-id> # Connection detail"]).build()}).withExamples(["sazabi integrations providers # List providers","sazabi integrations connect pagerduty --credentials '{...}' # Connect an integration","sazabi integrations connections list # List connections","sazabi integrations connections get <connection-id> # Connection detail"]).build();iA();$Q();import{readFile as M3A}from"node:fs/promises";uA();CA();var Cv={id:{label:"ID",type:{kind:"string"}},projectId:{label:"Project",type:{kind:"string"}},url:{label:"URL",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},status:{label:"Status",type:{kind:"string"}},severity:{label:"Severity",type:{kind:"severity"}},componentId:{label:"Component",type:{kind:"nullable-string"}},createdAt:{label:"Created",type:{kind:"date"}},resolvedAt:{label:"Resolved",type:{kind:"nullable-date"}},mutedAt:{label:"Muted",type:{kind:"nullable-date"}},muteHitCount:{label:"Mute hits",type:{kind:"number"}},lastActivityAt:{label:"Last activity",type:{kind:"nullable-date"}},lastDeliveredAt:{label:"Last delivered",type:{kind:"nullable-date"}},description:{label:"Description",type:{kind:"nullable-string"}},delivery:{label:"Delivery",type:{kind:"custom",render:(A)=>A==null?"(none)":JSON.stringify(A,null,2),serialize:(A)=>A??null}}},k3A={...Cv,duplicateIssueId:{label:"Reused issue",type:{kind:"nullable-string"}}},brA=["id","projectId","url","name","status","severity","componentId","createdAt","resolvedAt","mutedAt","muteHitCount","lastActivityAt","lastDeliveredAt","description"],lrA={schema:Cv,columns:["id","name","status","severity","createdAt","mutedAt","url"],jsonFields:brA,header:"Issues",emptyMessage:"No issues found."},Y3A={...lrA,jsonFields:[...brA,"delivery"]},Ie={layout:"sections",schema:Cv,primary:{title:"Issue",fields:["id","url","name","status","severity","createdAt","resolvedAt","mutedAt","muteHitCount","lastActivityAt","lastDeliveredAt","componentId"]},secondary:[{title:"Description",field:"description"}]},he=(A)=>({...A,url:$CA(A.projectId,A.id)}),$3A={...Ie,schema:k3A,secondary:[{title:"Reused existing issue",field:"duplicateIssueId"},...Ie.secondary??[]]},G3A={layout:"field-list",title:"Issue counts",schema:{total:{label:"Total",type:{kind:"number"}},byStatus:{label:"By status",type:{kind:"custom",render:(A)=>JSON.stringify(A),serialize:(A)=>A}},bySeverity:{label:"By severity",type:{kind:"custom",render:(A)=>JSON.stringify(A),serialize:(A)=>A}},filters:{label:"Filters",type:{kind:"custom",render:(A)=>JSON.stringify(A),serialize:(A)=>A},get:(A)=>A.filters}},fields:["total","byStatus","bySeverity","filters"]},T3A=fy.partial(),J3A={contentMdx:"contentMdx cannot be empty. Provide the issue body via --content-mdx or the contentMdx field in --from-json.",componentId:"componentId is required. Run `sazabi components list --json`, pick the matching component, and pass --component <id> (or componentId in --from-json)."},P3A=async(A)=>{let t=await j3A(A);if(!t.ok){if(A.json)return u(t.message);return D(t.message)}let g=R({tokenFlag:A.token,jsonMode:A.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),n=l(await i.issues.create(t.input),"Failed to create issue",A.json);W($3A,{...n.issue,duplicateIssueId:n.duplicateIssueId??null},{json:A.json})},R3A=async(A)=>{let t=R({tokenFlag:A.token,jsonMode:A.json}),g=f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=l(await g.issues.list({status:A.status,severity:A.severity,componentId:A.componentId,limit:A.limit,cursor:A.cursor}),"Couldn't list issues (check the active project and try again)",A.json);s(lrA,i.issues.map(he),{json:A.json,nextCursor:i.nextCursor})},f3A=async(A)=>{let t=R({tokenFlag:A.token,jsonMode:A.json}),g=f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=l(await g.issues.search({name:A.name,status:A.status,severity:A.severity,componentId:A.componentId,limit:A.limit,cursor:A.cursor,includeDeliveryMetadata:A.includeDeliveryMetadata}),"Couldn't search issues (check the active project and try again)",A.json);s(Y3A,i.issues.map(he),{json:A.json,nextCursor:i.nextCursor})},v3A=async(A)=>{let t=R({tokenFlag:A.token,jsonMode:A.json}),g=f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=l(await g.issues.count({name:A.name,status:A.status,severity:A.severity,componentId:A.componentId}),"Couldn't count issues (check the active project and try again)",A.json);W(G3A,i,{json:A.json})},O3A=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.issues.get(A),"Couldn't get issue (run 'sazabi issues list' to see issue IDs)",t.json);W(Ie,he(n.issue),{json:t.json})},z3A=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.issues.resolve(A),"Failed to resolve issue",t.json);W(Ie,he(n.issue),{json:t.json})},m3A=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.issues.reopen(A),"Failed to reopen issue",t.json);W(Ie,he(n.issue),{json:t.json})},W3A=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.issues.ignore(A),"Failed to ignore issue",t.json);W(Ie,he(n.issue),{json:t.json})},Z3A=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.issues.mute(A),"Failed to mute issue",t.json);W(Ie,he(n.issue),{json:t.json})},V3A=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.issues.unmute(A),"Failed to unmute issue",t.json);W(Ie,he(n.issue),{json:t.json})},j3A=async(A)=>{let t=A.fromJson?await H3A(A.fromJson):{ok:!0,input:{}};if(!t.ok)return t;let g={...t.input,...A.name!==void 0?{name:A.name}:{},...A.contentMdx!==void 0?{contentMdx:A.contentMdx}:{},...A.severity!==void 0?{severity:A.severity}:{},...A.componentId!==void 0?{componentId:A.componentId}:{}},i=vy.safeParse(g);if(!i.success)return{ok:!1,message:NrA(i.error)};return{ok:!0,input:i.data}},H3A=async(A)=>{let t;try{t=A==="-"?await X3A():await M3A(A,"utf8")}catch(n){return{ok:!1,message:`Couldn't read issue input (check that the --from-json path exists and is readable): ${n instanceof Error?n.message:String(n)}`}}let g;try{g=JSON.parse(t)}catch(n){return{ok:!1,message:`Couldn't parse issue input JSON (fix the JSON syntax and try again): ${n instanceof Error?n.message:String(n)}`}}let i=T3A.safeParse(g);if(!i.success)return{ok:!1,message:NrA(i.error)};return{ok:!0,input:i.data}},X3A=async()=>{let A=[];process.stdin.setEncoding("utf8");for await(let t of process.stdin)A.push(String(t));return A.join("")},NrA=(A)=>{let t=A.issues[0];if(!t)return"Invalid issue input.";let g=t.path[0];if(g&&t.code==="invalid_type")return J3A[g]??t.message;return t.message},UrA=nA("issues","Manage issues").withSubcommands({create:L("create","Create an issue, reusing an existing open issue when one matches",async(A)=>{let{values:t}=F(A,{...m,name:{type:"string"},"content-mdx":{type:"string"},severity:{type:"string"},component:{type:"string"},"from-json":{type:"string"}});await P3A({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],name:t.name,contentMdx:t["content-mdx"],severity:t.severity,componentId:t.component,fromJson:t["from-json"]})}).withOptions({...z,name:{type:"string",description:"Stable issue name for indexing and mute matching"},"content-mdx":{type:"string",description:"Safe Sazabi MDX document for the issue body (impact, root cause, remediation, evidence)"},severity:{type:"string",description:"Issue severity: low, medium, high, or critical (default: medium)"},component:{type:"string",description:"Required component ID. List with `sazabi components list` first; register one if none fits"},"from-json":{type:"string",description:"Read issue fields from a JSON file, or '-' for stdin"}}).withExamples(['sazabi issues create --content-mdx "Checkout is returning 500s due to pool exhaustion." --component "$COMPONENT_ID" # Create an issue from MDX content',"sazabi issues create --from-json issue.json # Create an issue from a JSON file with contentMdx","cat issue.json | sazabi issues create --from-json - --json # Create an issue from stdin"]).build(),list:L("list","List issues in the active project",async(A)=>{let{values:t}=F(A,{...m,status:{type:"string"},severity:{type:"string"},component:{type:"string"},limit:{type:"string"},cursor:{type:"string"}}),g=["open","resolved","ignored"];if(t.status&&!g.includes(t.status)){let o=`Invalid --status "${t.status}". Must be one of: ${g.join(", ")}.`;if(t.json)return u(o);return D(o)}let i=["low","medium","high","critical"];if(t.severity&&!i.includes(t.severity)){let o=`Invalid --severity "${t.severity}". Must be one of: ${i.join(", ")}.`;if(t.json)return u(o);return D(o)}let n=t.limit?Number(t.limit):void 0;if(n!==void 0&&(Number.isNaN(n)||n<1||n>100)){if(t.json)return u("Invalid --limit. Must be an integer between 1 and 100.");return D("Invalid --limit. Must be an integer between 1 and 100.")}await R3A({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],status:t.status,severity:t.severity,componentId:t.component,limit:n,cursor:t.cursor})}).withOptions({...z,status:{type:"string",description:"Filter by status: open, resolved, or ignored"},severity:{type:"string",description:"Filter by severity: low, medium, high, or critical"},component:{type:"string",description:"Filter by component ID"},limit:{type:"string",description:"Maximum number of issues to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from previous response"}}).withExamples(["sazabi issues list # List all issues","sazabi issues list --status open # List open issues only","sazabi issues list --component <component-id> # List issues for a component"]).build(),search:L("search","Search issues by name and filters",async(A)=>{let{values:t,positionals:g}=F(A,{...m,name:{type:"string"},status:{type:"string"},severity:{type:"string"},component:{type:"string"},limit:{type:"string"},cursor:{type:"string"},"include-delivery-metadata":{type:"boolean"}},{allowPositionals:!0}),i=["open","resolved","ignored"];if(t.status&&!i.includes(t.status)){let I=`Invalid --status "${t.status}". Must be one of: ${i.join(", ")}.`;if(t.json)return u(I);return D(I)}let n=["low","medium","high","critical"];if(t.severity&&!n.includes(t.severity)){let I=`Invalid --severity "${t.severity}". Must be one of: ${n.join(", ")}.`;if(t.json)return u(I);return D(I)}let o=t.limit?Number(t.limit):void 0;if(o!==void 0&&(Number.isNaN(o)||o<1||o>100)){if(t.json)return u("Invalid --limit. Must be an integer between 1 and 100.");return D("Invalid --limit. Must be an integer between 1 and 100.")}let e=g.join(" ").trim();await f3A({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],name:t.name??(e||void 0),status:t.status,severity:t.severity,componentId:t.component,limit:o,cursor:t.cursor,includeDeliveryMetadata:t["include-delivery-metadata"]})}).withPositionalArgs("[name]").withOptions({...z,name:{type:"string",description:"Case-insensitive partial issue name match"},status:{type:"string",description:"Filter by status: open, resolved, or ignored"},severity:{type:"string",description:"Filter by severity: low, medium, high, or critical"},component:{type:"string",description:"Filter by component ID"},limit:{type:"string",description:"Maximum number of issues to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from previous response"},"include-delivery-metadata":{type:"boolean",description:"Include delivery metadata in JSON output"}}).withExamples(['sazabi issues search "checkout" --status open # Search open issues by name',"sazabi issues search --severity critical --json # Machine-readable search"]).build(),count:L("count","Count issues by status and severity",async(A)=>{let{values:t,positionals:g}=F(A,{...m,name:{type:"string"},status:{type:"string"},severity:{type:"string"},component:{type:"string"}},{allowPositionals:!0}),i=["open","resolved","ignored"];if(t.status&&!i.includes(t.status)){let e=`Invalid --status "${t.status}". Must be one of: ${i.join(", ")}.`;if(t.json)return u(e);return D(e)}let n=["low","medium","high","critical"];if(t.severity&&!n.includes(t.severity)){let e=`Invalid --severity "${t.severity}". Must be one of: ${n.join(", ")}.`;if(t.json)return u(e);return D(e)}let o=g.join(" ").trim();await v3A({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],name:t.name??(o||void 0),status:t.status,severity:t.severity,componentId:t.component})}).withPositionalArgs("[name]").withOptions({...z,name:{type:"string",description:"Case-insensitive partial issue name match"},status:{type:"string",description:"Filter by status: open, resolved, or ignored"},severity:{type:"string",description:"Filter by severity: low, medium, high, or critical"},component:{type:"string",description:"Filter by component ID"}}).withExamples(["sazabi issues count --status open # Count open issues",'sazabi issues count "checkout" --json # Count matching issues']).build(),get:L("get","Get one issue by ID",async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Issue ID is required.");return D("Issue ID is required.")}await O3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<issue-id>").withOptions(z).withExamples(["sazabi issues get <issue-id> # Get one issue"]).build(),resolve:L("resolve","Resolve an open issue",async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Issue ID is required.");return D("Issue ID is required.")}await z3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<issue-id>").withOptions(z).withExamples(["sazabi issues resolve <issue-id> # Resolve an issue"]).build(),ignore:L("ignore","Ignore an issue",async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Issue ID is required.");return D("Issue ID is required.")}await W3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<issue-id>").withOptions(z).withExamples(["sazabi issues ignore <issue-id> # Ignore an issue"]).build(),reopen:L("reopen","Reopen a resolved or ignored issue",async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Issue ID is required.");return D("Issue ID is required.")}await m3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<issue-id>").withOptions(z).withExamples(["sazabi issues reopen <issue-id> # Reopen a resolved or ignored issue"]).build(),mute:L("mute","Mute an issue",async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Issue ID is required.");return D("Issue ID is required.")}await Z3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<issue-id>").withOptions(z).withExamples(["sazabi issues mute <issue-id> # Mute an issue"]).build(),unmute:L("unmute","Unmute an issue",async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Issue ID is required.");return D("Issue ID is required.")}await V3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<issue-id>").withOptions(z).withExamples(["sazabi issues unmute <issue-id> # Unmute an issue"]).build()}).withExamples(["sazabi issues create --from-json issue.json # Create an issue","sazabi issues list # List all issues","sazabi issues search checkout # Search issues","sazabi issues count --status open # Count issues","sazabi issues get <issue-id> # Get one issue","sazabi issues resolve <issue-id> # Resolve an issue","sazabi issues ignore <issue-id> # Ignore an issue","sazabi issues mute <issue-id> # Mute an issue","sazabi issues unmute <issue-id> # Unmute an issue"]).build();iA();uA();CA();var K3A=async(A,t)=>{let g=R({tokenFlag:t.token,projectIdFlag:A==="public"?t.projectId:void 0,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:A==="public"?g.projectId:void 0,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json});if(A==="public"){let o=l(await i.publicKeys.list({projectId:g.projectId,limit:t.limit,cursor:t.cursor}),"Couldn't list public keys (check the active project and try again)",t.json);s(LrA(A),o.publicKeys.map((e)=>Be(A,e)),{json:t.json,nextCursor:o.nextCursor});return}let n=l(await i.secretKeys.list({limit:t.limit,cursor:t.cursor}),"Couldn't list secret keys (check your organization access and try again)",t.json);s(LrA(A),n.secretKeys.map((o)=>Be(A,o)),{json:t.json,nextCursor:n.nextCursor})},_3A=async(A,t,g)=>{let i=R({tokenFlag:g.token,projectIdFlag:A==="public"?g.projectId:void 0,jsonMode:g.json}),n=f({token:i.token,organizationId:i.organizationId,projectId:A==="public"?i.projectId:void 0,apiBaseUrlFlag:g.apiBaseUrl,jsonMode:g.json});if(A==="public"){let e=l(await n.publicKeys.get(t,i.projectId),"Couldn't get public key (run 'sazabi public-keys list' to see key IDs)",g.json);W(TB(A),Be(A,e.publicKey),{json:g.json});return}let o=l(await n.secretKeys.get(t),"Couldn't get secret key (run 'sazabi secret-keys list' to see key IDs)",g.json);W(TB(A),Be(A,o.secretKey),{json:g.json})},s3A=async(A,t)=>{let i=R({tokenFlag:t.token,projectIdFlag:void 0,jsonMode:t.json}),n=f({token:i.token,organizationId:i.organizationId,projectId:void 0,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),o={name:A,...t.expiresAt?{expiresAt:t.expiresAt}:{}},e=l(await n.secretKeys.create(o),"Failed to create secret key",t.json);if(t.json){X(e);return}x(`Secret key ${e.secretKey.name} created.`),zA({Value:e.secretKey.value}),W(TB("secret"),{...Be("secret",e.secretKey)})},x3A=async(A,t,g)=>{if(g.name===void 0&&g.expiresAt===void 0&&!g.clearExpiresAt){if(g.json)return u("At least one update is required. Pass --name, --expires-at, or --clear-expires-at.");return D("At least one update is required. Pass --name, --expires-at, or --clear-expires-at.")}if(g.expiresAt&&g.clearExpiresAt){if(g.json)return u("Use either --expires-at or --clear-expires-at, not both.");return D("Use either --expires-at or --clear-expires-at, not both.")}let i=R({tokenFlag:g.token,projectIdFlag:A==="public"?g.projectId:void 0,jsonMode:g.json}),n=f({token:i.token,organizationId:i.organizationId,projectId:A==="public"?i.projectId:void 0,apiBaseUrlFlag:g.apiBaseUrl,jsonMode:g.json}),o=g.clearExpiresAt?null:g.expiresAt!==void 0?g.expiresAt:void 0;if(A==="public"){let h={projectId:i.projectId,keyId:t,...g.name!==void 0?{name:g.name}:{},...o!==void 0?{expiresAt:o}:{}},B=l(await n.publicKeys.update(h),"Failed to update public key",g.json);W(TB(A),Be(A,B.publicKey),{json:g.json});return}let e={keyId:t,...g.name!==void 0?{name:g.name}:{},...o!==void 0?{expiresAt:o}:{}},I=l(await n.secretKeys.update(e),"Failed to update secret key",g.json);W(TB(A),Be(A,I.secretKey),{json:g.json})},q3A=async(A,t)=>{let g=R({tokenFlag:t.token,projectIdFlag:t.projectId,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.publicKeys.deactivate({projectId:g.projectId,keyId:A}),"Failed to deactivate public key",t.json);if(!t.json)x(`Public key ${A} deactivated.`);W(TB("public"),Be("public",n.publicKey),{json:t.json})},d3A=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json});if(l(await i.secretKeys.delete({keyId:A}),"Failed to delete secret key",t.json),t.json){X({deleted:!0,keyId:A});return}x(`Secret key ${A} deleted.`)},SrA=(A)=>{let t=p3A(A),g=rv(A),i=A==="secret",n=i?"the organization":"the active project",o={token:{type:"string"},"project-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},h=i?{token:{type:"string",description:"Override token"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}:{token:{type:"string",description:"Override token"},"project-id":{type:"string",description:"Override project selection"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}};return nA(t,`Manage ${A} keys`).withSubcommands({list:L("list",`List ${A} keys in ${n}`,async(B)=>{let{values:c,positionals:C}=F(B,{...o,limit:{type:"string"},cursor:{type:"string"}},{allowPositionals:!0});if(C.length>0){let r=C.join(", ");if(c.json)return u(`Unexpected arguments: ${r}.`);return D(`Unexpected arguments: ${r}.`)}await K3A(A,{token:c.token,projectId:c["project-id"],limit:c.limit?Number(c.limit):void 0,cursor:c.cursor,json:c.json,apiBaseUrl:c["api-base-url"]})}).withOptions({...h,limit:{type:"string",description:"Maximum number of keys to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from previous response"}}).withExamples([`sazabi ${t} list # List ${A} keys in ${n}`]).build(),get:L("get",`Get one ${A} key by ID`,async(B)=>{let{values:c,positionals:C}=F(B,o,{allowPositionals:!0}),r=C[0];if(!r){let a=`${g} key ID is required.`;if(c.json)return u(a);return D(a)}await _3A(A,r,{token:c.token,projectId:c["project-id"],json:c.json,apiBaseUrl:c["api-base-url"]})}).withPositionalArgs("<key-id>").withOptions(h).withExamples([`sazabi ${t} get <key-id> # Get one ${A} key`]).build(),...i?{create:L("create",`Create one ${A} key in ${n}`,async(B)=>{let{values:c,positionals:C}=F(B,{...o,"expires-at":{type:"string"}},{allowPositionals:!0}),r=C.join(" ");if(!r){let a=`${g} key name is required.`;if(c.json)return u(a);return D(a)}await s3A(r,{token:c.token,projectId:c["project-id"],expiresAt:c["expires-at"],json:c.json,apiBaseUrl:c["api-base-url"]})}).withPositionalArgs("<name>").withOptions({...h,"expires-at":{type:"string",description:"Optional ISO timestamp when the key should expire"}}).withExamples([`sazabi ${t} create "CI agent" # Create one ${A} key`]).build()}:{},update:L("update",`Update one ${A} key in ${n}`,async(B)=>{let{values:c,positionals:C}=F(B,{...o,name:{type:"string"},"expires-at":{type:"string"},"clear-expires-at":{type:"boolean"}},{allowPositionals:!0}),r=C[0];if(!r){let a=`${g} key ID is required.`;if(c.json)return u(a);return D(a)}await x3A(A,r,{token:c.token,projectId:c["project-id"],name:c.name,expiresAt:c["expires-at"],clearExpiresAt:c["clear-expires-at"],json:c.json,apiBaseUrl:c["api-base-url"]})}).withPositionalArgs("<key-id>").withOptions({...h,name:{type:"string",description:`New ${A} key name`},"expires-at":{type:"string",description:"New ISO timestamp when the key should expire"},"clear-expires-at":{type:"boolean",description:"Clear any configured expiration"}}).withExamples([`sazabi ${t} update <key-id> --name "Renamed key" # Update one ${A} key`]).build(),...A==="public"?{deactivate:L("deactivate",`Deactivate one public key in ${n}`,async(B)=>{let{values:c,positionals:C}=F(B,o,{allowPositionals:!0}),r=C[0];if(!r){if(c.json)return u("Public key ID is required.");return D("Public key ID is required.")}await q3A(r,{token:c.token,projectId:c["project-id"],json:c.json,apiBaseUrl:c["api-base-url"]})}).withPositionalArgs("<key-id>").withOptions(h).withExamples([`sazabi ${t} deactivate <key-id> # Deactivate one public key`]).build()}:{delete:L("delete",`Delete one secret key from ${n}`,async(B)=>{let{values:c,positionals:C}=F(B,o,{allowPositionals:!0}),r=C[0];if(!r){if(c.json)return u("Secret key ID is required.");return D("Secret key ID is required.")}await d3A(r,{token:c.token,json:c.json,apiBaseUrl:c["api-base-url"]})}).withPositionalArgs("<key-id>").withOptions(h).withExamples([`sazabi ${t} delete <key-id> # Delete one secret key`]).build()}}).withExamples([`sazabi ${t} list # List ${A} keys in ${n}`,...i?[`sazabi ${t} create "CI agent" # Create one ${A} key`]:[]]).build()},FrA={keyType:{label:"Type",type:{kind:"string"}},id:{label:"ID",type:{kind:"string"}},projectId:{label:"Project ID",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},status:{label:"Status",type:{kind:"string"}},expiresAt:{label:"Expires",type:{kind:"nullable-date"}},lastUsedAt:{label:"Last used",type:{kind:"nullable-date"}},createdAt:{label:"Created",type:{kind:"date"}}},LrA=(A)=>({schema:FrA,columns:A==="public"?["id","name","status","expiresAt","lastUsedAt","createdAt"]:["id","name","expiresAt","lastUsedAt","createdAt"],header:`${rv(A)} keys`,emptyMessage:`No ${A} keys found.`}),TB=(A)=>({layout:"field-list",schema:FrA,fields:A==="public"?["keyType","id","projectId","name","status","expiresAt","lastUsedAt","createdAt"]:["keyType","id","name","expiresAt","lastUsedAt","createdAt"]}),p3A=(A)=>{return A==="public"?"public-keys":"secret-keys"},rv=(A)=>{return A==="public"?"Public":"Secret"},Be=(A,t)=>{let g=A==="public"&&"deactivatedAt"in t&&t.deactivatedAt!==null;return{...t,keyType:`${rv(A)} key`,status:g?"Deactivated":"Active"}},MrA=SrA("public"),krA=SrA("secret");iA();uA();CA();var oa=(A)=>({id:A.id,projectId:A.projectId,name:A.name,expression:A.expression,enabled:A.enabled,compiledVersion:A.compiledVersion,linkedAutomationIds:A.linkedAutomationIds??[],createdAt:A.createdAt,updatedAt:A.updatedAt}),YrA={id:{label:"ID",type:{kind:"id"}},projectId:{label:"Project ID",type:{kind:"id"}},name:{label:"Name",type:{kind:"string"}},expression:{label:"Expression",type:{kind:"string"}},enabled:{label:"Enabled",type:{kind:"custom",render:(A)=>A?"Yes":"No",serialize:(A)=>A}},compiledVersion:{label:"Compiled version",type:{kind:"number"}},linkedAutomationIds:{label:"Linked automations",type:{kind:"custom",render:(A)=>Array.isArray(A)&&A.length>0?A.join(", "):"(none)",serialize:(A)=>A}},createdAt:{label:"Created at",type:{kind:"nullable-date"}},updatedAt:{label:"Updated at",type:{kind:"nullable-date"}}},A7A={schema:YrA,columns:["name","enabled","updatedAt"],jsonFields:["id","projectId","name","expression","enabled","compiledVersion","linkedAutomationIds","updatedAt"],header:"Log-match expressions",emptyMessage:"No log-match expressions found."},Hb={layout:"field-list",schema:YrA,fields:["id","projectId","name","expression","enabled","compiledVersion","linkedAutomationIds","createdAt","updatedAt"],title:"Log-match expression"},na={...z,"project-id":{type:"string",description:"Override active project ID"}},ia={...m,"project-id":{type:"string"}},ea=(A)=>{let t=R({tokenFlag:A.token,projectIdFlag:A.projectId,jsonMode:A.json});return{client:f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json})}},av=(A,t)=>{let g=A[0]?.trim();if(!g){if(t){u("Expression ID is required.");return}D("Expression ID is required.");return}return g},t7A=(A,t)=>{let g=A[0]?.trim();if(!g){if(t){u("Expression name is required.");return}D("Expression name is required.");return}return g},g7A=async(A)=>{let{client:t}=ea(A),g=l(await t.logMatchExpressions.list(),"Couldn't list log-match expressions",A.json);s(A7A,g.expressions.map(oa),{json:A.json})},n7A=async(A,t)=>{let{client:g}=ea(t),i=l(await g.logMatchExpressions.get(A),"Couldn't get log-match expression (run 'sazabi log-match-expressions list' to see IDs)",t.json);W(Hb,oa(i.expression),{json:t.json})},i7A=async(A,t)=>{if(!t.expression?.trim()){if(t.json){u("CEL expression is required. Pass --expression '<CEL>'.");return}D("CEL expression is required. Pass --expression '<CEL>'.");return}if(t.enabled===!0&&t.disabled===!0){if(t.json){u("Use either --enabled or --disabled, not both.");return}D("Use either --enabled or --disabled, not both.");return}let g=t.disabled===!0?!1:t.enabled===!0?!0:void 0,{client:i}=ea(t),n=l(await i.logMatchExpressions.create({name:A,expression:t.expression,...g!==void 0?{enabled:g}:{}}),"Couldn't create log-match expression",t.json);if(!t.json)x(`Log-match expression "${n.expression.name}" created.`);W(Hb,oa(n.expression),{json:t.json})},o7A=async(A,t)=>{if(t.name===void 0&&t.expression===void 0&&t.enable!==!0&&t.disable!==!0){if(t.json){u("Nothing to update. Provide --name, --expression, --enable, or --disable.");return}D("Nothing to update. Provide --name, --expression, --enable, or --disable.");return}if(t.enable===!0&&t.disable===!0){if(t.json){u("Use either --enable or --disable, not both.");return}D("Use either --enable or --disable, not both.");return}let g=t.disable===!0?!1:t.enable===!0?!0:void 0,{client:i}=ea(t),n=l(await i.logMatchExpressions.update(A,{...t.name!==void 0?{name:t.name}:{},...t.expression!==void 0?{expression:t.expression}:{},...g!==void 0?{enabled:g}:{}}),"Couldn't update log-match expression",t.json);if(!t.json)x(`Log-match expression "${n.expression.name}" updated.`);W(Hb,oa(n.expression),{json:t.json})},e7A=async(A,t)=>{let{client:g}=ea(t),i=l(await g.logMatchExpressions.disable(A),"Couldn't disable log-match expression",t.json);if(!t.json)x(`Log-match expression "${i.expression.name}" disabled.`);W(Hb,oa(i.expression),{json:t.json})},$rA=nA("log-match-expressions","Manage CEL log-match expressions").withSubcommands({list:L("list","List log-match expressions",async(A)=>{let{values:t}=F(A,ia);await g7A({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions(na).withExamples(["sazabi log-match-expressions list --json # List log-match expressions"]).build(),get:L("get","Get one log-match expression by ID",async(A)=>{let{values:t,positionals:g}=F(A,ia,{allowPositionals:!0}),i=av(g,t.json);if(!i)return;await n7A(i,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<expression-id>").withOptions(na).withExamples(["sazabi log-match-expressions get <expression-id> --json # Get one expression"]).build(),create:L("create","Create a log-match expression",async(A)=>{let{values:t,positionals:g}=F(A,{...ia,expression:{type:"string"},enabled:{type:"boolean"},disabled:{type:"boolean"}},{allowPositionals:!0}),i=t7A(g,t.json);if(!i)return;let n=(o)=>{if(t.json){u(o);return}D(o)};await i7A(i,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],expression:t.expression,enabled:t.enabled,disabled:t.disabled})}).withPositionalArgs("<name>").withOptions({...na,expression:{type:"string",description:"CEL expression evaluated against ingested logs"},enabled:{type:"boolean",description:"Create the expression enabled"},disabled:{type:"boolean",description:"Create the expression disabled"}}).withExamples([`sazabi log-match-expressions create plain-tickets --expression 'service == "plain"' --json # Create an expression`]).build(),update:L("update","Update a log-match expression",async(A)=>{let{values:t,positionals:g}=F(A,{...ia,name:{type:"string"},expression:{type:"string"},enable:{type:"boolean"},disable:{type:"boolean"}},{allowPositionals:!0}),i=av(g,t.json);if(!i)return;let n=(o)=>{if(t.json){u(o);return}D(o)};await o7A(i,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],name:t.name,expression:t.expression,enable:t.enable,disable:t.disable})}).withPositionalArgs("<expression-id>").withOptions({...na,name:{type:"string",description:"New expression name"},expression:{type:"string",description:"New CEL expression body"},enable:{type:"boolean",description:"Enable the expression"},disable:{type:"boolean",description:"Disable the expression"}}).withExamples([`sazabi log-match-expressions update <expression-id> --expression 'severity == "ERROR"' --json # Update expression CEL`]).build(),disable:L("disable","Disable a log-match expression",async(A)=>{let{values:t,positionals:g}=F(A,ia,{allowPositionals:!0}),i=av(g,t.json);if(!i)return;await e7A(i,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<expression-id>").withOptions(na).withExamples(["sazabi log-match-expressions disable <expression-id> --json # Disable an expression"]).build()}).build();iA();uA();CA();iA();uA();CA();var TrA={id:{label:"ID",type:{kind:"string"}},displayName:{label:"Name",type:{kind:"nullable-string"}},logSourceId:{label:"Log source",type:{kind:"string"}},status:{label:"Status",type:{kind:"string"}},enabled:{label:"Enabled",type:{kind:"boolean"}},errorMessage:{label:"Error",type:{kind:"nullable-string"}},createdAt:{label:"Created",type:{kind:"date"}}},Ev={schema:TrA,columns:["id","displayName","status","enabled","errorMessage","createdAt"],header:"Log streams",emptyMessage:"No log streams found for this log source."},Q7A={layout:"field-list",schema:TrA,fields:["id","logSourceId","displayName","status","enabled","errorMessage","createdAt"],title:"Log stream"},Xb=(A)=>{for(let t of A){let g={};if(t.kind==="url"&&t.url)g[t.label??"Endpoint"]=t.url;else if(t.kind==="hostPort"&&t.host){if(g[t.label??"Host"]=t.port!==void 0?`${t.host}:${t.port}`:t.host,t.extraCredential)g[t.extraCredential.label]=t.extraCredential.value}if(Object.keys(g).length>0){if(zA(g),t.description)IA(t.description)}}},Vg=(A)=>{let t=A.json,g=R({tokenFlag:A.token,jsonMode:t});return{client:f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:t}),json:t,projectId:g.projectId}},Kb=(A,t)=>{let g=A[0];if(!g){if(t)u("Log stream ID is required.");else D("Log stream ID is required. Run 'sazabi log-streams list --log-source-id <id>' to see log stream IDs.");return null}return g},I7A=async(A)=>{let{values:t}=F(A,{...m,"log-source-id":{type:"string"}});if(!t["log-source-id"]){if(t.json)return u("--log-source-id is required.");return D("--log-source-id is required. Run 'sazabi log-sources list' to see log source IDs.")}let{client:g,json:i}=Vg(t),{streams:n}=l(await g.logStreams.list(t["log-source-id"]),"Couldn't list log streams (run 'sazabi log-sources list' to see log source IDs)",i);s(Ev,n,{json:i})},h7A=async(A)=>{let{values:t}=F(A,{...m,"log-source-id":{type:"string"},config:{type:"string"}});if(!t["log-source-id"]){if(t.json)return u("--log-source-id is required.");return D("--log-source-id is required.")}let g={};if(t.config)try{g=JSON.parse(t.config)}catch{if(t.json)return u("--config must be valid JSON.");return D("--config must be valid JSON.")}let{client:i,json:n}=Vg(t),o=l(await i.logStreams.create({logSourceId:t["log-source-id"],config:g}),"Failed to create log stream",n);if(n){X(o);return}x("Log stream created. Provisioning started."),zA({"Log stream ID":o.streamId})},B7A=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=Kb(g,t.json);if(!i)return;let{client:n,json:o}=Vg(t),{stream:e}=l(await n.logStreams.get(i),"Couldn't get log stream (run 'sazabi log-streams list --log-source-id <id>' to see log stream IDs)",o);if(o){X({stream:e});return}if(W(Q7A,e,{json:o}),e.endpointCards&&e.endpointCards.length>0)IA("Point your sender at:"),Xb(e.endpointCards)},GrA=async(A,t)=>{let{values:g,positionals:i}=F(A,m,{allowPositionals:!0}),n=Kb(i,g.json);if(!n)return;let{client:o,json:e}=Vg(g),I=l(await o.logStreams.update({streamId:n,enabled:t}),t?"Failed to enable log stream":"Failed to disable log stream",e);if(e){X(I);return}x(t?"Log stream enabled. It resumes ingesting.":"Log stream disabled. It stops ingesting until re-enabled.")},c7A=async(A)=>{let{values:t,positionals:g}=F(A,{...m,"to-log-source-id":{type:"string"}},{allowPositionals:!0}),i=Kb(g,t.json);if(!i)return;let n=t["to-log-source-id"];if(!n){if(t.json)return u("--to-log-source-id is required.");return D("--to-log-source-id is required. Run 'sazabi log-sources list' to see log source IDs.")}let{client:o,json:e}=Vg(t),{stream:I}=l(await o.logStreams.get(i),"Couldn't get log stream (run 'sazabi log-streams list --log-source-id <id>' to see log stream IDs)",e),{logSource:h}=l(await o.logSources.get(I.logSourceId),"Couldn't get the log stream's current log source",e),{logSource:B}=l(await o.logSources.get(n),"Couldn't get the target log source (run 'sazabi log-sources list' to see log source IDs)",e),c=l(await o.logStreams.reassign({streamId:i,targetLogSourceId:n}),"Failed to reassign log stream",e);if(e){X(c);return}if(x("Log stream reassigned."),zA({"Log stream ID":c.stream.id,From:`${h.name} (${h.provider})`,To:`${B.name} (${B.provider})`}),h.provider!==B.provider)IA(`The log stream keeps its intake key, but future data is now processed as ${B.provider} format — make sure the sender emits that format. Already-ingested data is unaffected.`)},C7A=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=Kb(g,t.json);if(!i)return;let{client:n,json:o}=Vg(t),e=l(await n.logStreams.delete(i),"Failed to delete log stream",o);if(o){X(e);return}x("Log stream deleted.")},JrA=nA("log-streams","Manage log streams").withSubcommands({list:L("list","List log streams for a log source",I7A).withOptions({...z,"log-source-id":{type:"string",description:"Log source ID (required)"}}).withExamples(["sazabi log-streams list --log-source-id <id> # List log streams"]).build(),get:L("get","Get one log stream (check provisioning status)",B7A).withPositionalArgs("<stream-id>").withOptions(z).withExamples(["sazabi log-streams get <id> # Check log stream status"]).build(),create:L("create","Create a log stream under a managed log source",h7A).withOptions({...z,"log-source-id":{type:"string",description:"Log source ID (required)"},config:{type:"string",description:"JSON stream config"}}).withExamples([`sazabi log-streams create --log-source-id <id> --config '{"foo":"bar"}' # Create log stream`]).build(),enable:L("enable","Resume ingestion for a log stream",(A)=>GrA(A,!0)).withPositionalArgs("<stream-id>").withOptions(z).withExamples(["sazabi log-streams enable <id> # Resume ingestion"]).build(),disable:L("disable","Pause ingestion for a log stream",(A)=>GrA(A,!1)).withPositionalArgs("<stream-id>").withOptions(z).withExamples(["sazabi log-streams disable <id> # Pause ingestion"]).build(),reassign:L("reassign","Move a log stream to a different connectionless log source",c7A).withPositionalArgs("<stream-id>").withOptions({...z,"to-log-source-id":{type:"string",description:"Target log source ID (required)"}}).withExamples(["sazabi log-streams reassign <id> --to-log-source-id <id> # Move a log stream"]).build(),delete:L("delete","Delete a log stream",C7A).withPositionalArgs("<stream-id>").withOptions(z).withExamples(["sazabi log-streams delete <id> # Delete a log stream"]).build()}).withExamples(["sazabi log-streams list --log-source-id <id> # List log streams","sazabi log-streams get <id> # Log stream detail and endpoint","sazabi log-streams reassign <id> --to-log-source-id <id> # Move a log stream","sazabi log-streams delete <id> # Delete a log stream"]).build();var r7A={id:{label:"ID",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},modes:{label:"Modes",type:{kind:"string"}}},a7A={schema:r7A,columns:["id","name","modes"],header:"Log source providers",emptyMessage:"No log source providers found."},vrA={id:{label:"ID",type:{kind:"string"}},provider:{label:"Provider",type:{kind:"string"}},mode:{label:"Mode",type:{kind:"string"}},name:{label:"Name",type:{kind:"nullable-string"}},streamCount:{label:"Streams",type:{kind:"number"}},url:{label:"URL",type:{kind:"nullable-string"}},createdAt:{label:"Created",type:{kind:"date"}}},E7A={schema:vrA,columns:["id","provider","mode","name","streamCount","createdAt"],header:"Log sources",emptyMessage:"No log sources found."},y7A={layout:"field-list",schema:vrA,fields:["id","provider","mode","name","streamCount","url","createdAt"],title:"Log source"},w7A=(A,t)=>({...A,url:t?JCA(t,A.provider):void 0}),yv=(A,t)=>{let g=A[0];if(!g){if(t)u("Log source ID is required.");else D("Log source ID is required. Run 'sazabi log-sources list' to see log source IDs.");return null}return g},D7A=async(A)=>{let{values:t}=F(A,m),{client:g,json:i}=Vg(t),{providers:n}=l(await g.logSources.listProviders(),"Couldn't list log source providers (try again)",i),o=[...n].sort((e,I)=>e.name.localeCompare(I.name)).map((e)=>({id:e.id,name:e.name,modes:e.modes.join(", ")}));s(a7A,o,{json:i})},u7A=async(A)=>{let{values:t}=F(A,{...m,provider:{type:"string"},"project-id":{type:"string"}}),{client:g,json:i}=Vg(t),{logSources:n}=l(await g.logSources.list({projectId:t["project-id"],provider:t.provider}),"Couldn't list log sources (check the active project and try again)",i);s(E7A,n,{json:i})},b7A=async(A)=>{let{values:t,positionals:g}=F(A,{...m,metadata:{type:"string"},mode:{type:"string"},"project-id":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Log source provider is required.");return D("Log source provider is required. Use 'sazabi log-sources providers' to see available providers.")}if(t.mode&&t.mode!=="managed"&&t.mode!=="connectionless"){if(t.json)return u("--mode must be 'managed' or 'connectionless'.");return D("--mode must be 'managed' or 'connectionless'.")}let n;if(t.metadata)try{n=JSON.parse(t.metadata)}catch{if(t.json)return u("--metadata must be valid JSON.");return D("--metadata must be valid JSON.")}let{client:o,json:e}=Vg(t),I=l(await o.logSources.create({provider:i,metadata:n,mode:t.mode,projectId:t["project-id"]}),"Failed to create log source",e);if(e){X(I);return}if(x("Log source created."),zA({"Log source ID":I.logSource.id,...I.logSource.name?{Name:I.logSource.name}:{},Provider:I.logSource.provider,Mode:I.logSource.mode,...I.streamId?{"Log stream ID":I.streamId}:{},...I.publicKey?{"Public key":I.publicKey}:{}}),I.endpointCards&&I.endpointCards.length>0)IA("Point your sender at:"),Xb(I.endpointCards);if(I.publicKey)jg("Store the public key securely — it is only shown once.")},l7A=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=yv(g,t.json);if(!i)return;let{client:n,json:o,projectId:e}=Vg(t),{logSource:I}=l(await n.logSources.get(i),"Couldn't get log source (run 'sazabi log-sources list' to see log source IDs)",o);if(o){X({logSource:I});return}if(W(y7A,w7A({id:I.id,provider:I.provider,mode:I.mode,name:I.name,streamCount:I.streamCount,createdAt:I.createdAt},e),{json:o}),I.streams.length>0){s(Ev,I.streams,{json:o});for(let h of I.streams)if(h.endpointCards&&h.endpointCards.length>0)IA(`Endpoint for log stream "${h.displayName??h.id}":`),Xb(h.endpointCards)}},PrA=async(A,t)=>{let{values:g,positionals:i}=F(A,m,{allowPositionals:!0}),n=yv(i,g.json);if(!n)return;let{client:o,json:e}=Vg(g),I=l(await o.logSources.update({logSourceId:n,enabled:t}),t?"Failed to enable log source":"Failed to disable log source",e);if(e){X(I);return}x(t?"Log source enabled. Its log streams resume ingesting.":"Log source disabled. Its log streams stop ingesting until re-enabled.")},N7A=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=yv(g,t.json);if(!i)return;let{client:n,json:o}=Vg(t),e=l(await n.logSources.delete(i),"Failed to delete log source",o);if(o){X(e);return}if(e.teardownError){jg(`Log source deleted, but remote cleanup failed (remove the remote resources manually): ${e.teardownError}`);return}x("Log source deleted.")},U7A=async(A)=>{let{values:t}=F(A,{...m,provider:{type:"string"}});if(!t.provider){if(t.json)return u("--provider is required.");return D("--provider is required. Use 'sazabi log-sources providers' to see providers with skills.")}let{client:g,json:i}=Vg(t),{providers:n}=l(await g.logSources.listProviders(),"Couldn't list log source providers (try again)",i),o=n.find((e)=>e.id===t.provider);if(!o){let e=`Unknown log source provider: '${t.provider}'. Use 'sazabi log-sources providers' to see available providers.`;if(i)return u(e);return D(e)}if(!o.setupSkill){if(i)return u(`No setup skill available for ${t.provider}.`);return D(`No setup skill available for ${t.provider}. This log source provider does not have an agent-ready skill yet.`)}if(i){X({provider:t.provider,setupSkill:o.setupSkill});return}IA(o.setupSkill)},RrA=L("list","List log sources",u7A).withOptions({...z,provider:{type:"string",description:"Filter by log source provider"},"project-id":{type:"string",description:"Project ID"}}).withExamples(["sazabi log-sources list # List all log sources","sazabi log-sources list --provider vercel # Filter by provider"]).build(),frA=L("delete","Delete a log source",N7A).withPositionalArgs("<log-source-id>").withOptions(z).withExamples(["sazabi log-sources delete <id> # Delete a log source and deactivate its keys"]).build(),OrA=nA("log-sources","Manage log sources").withSubcommands({providers:L("providers","List supported log source providers",D7A).withOptions(z).withExamples(["sazabi log-sources providers # List all providers","sazabi log-sources providers --json # Output as JSON"]).build(),list:RrA,ls:RrA,create:L("create","Create a log source",b7A).withPositionalArgs("<provider>").withOptions({...z,metadata:{type:"string",description:"JSON credentials for managed setup"},mode:{type:"string",description:"Setup mode: managed or connectionless (inferred from --metadata when omitted)"},"project-id":{type:"string",description:"Project ID"}}).withExamples(["sazabi log-sources create otel # Connectionless: mints a keyed endpoint",`sazabi log-sources create fly_io --metadata '{"apiToken":"..."}' # Managed: connects with credentials`]).build(),get:L("get","Get one log source",l7A).withPositionalArgs("<log-source-id>").withOptions(z).withExamples(["sazabi log-sources get <id> # Log source details, log streams, and endpoints"]).build(),enable:L("enable","Resume ingestion for a log source's log streams",(A)=>PrA(A,!0)).withPositionalArgs("<log-source-id>").withOptions(z).withExamples(["sazabi log-sources enable <id> # Resume ingestion"]).build(),disable:L("disable","Pause ingestion for a log source's log streams",(A)=>PrA(A,!1)).withPositionalArgs("<log-source-id>").withOptions(z).withExamples(["sazabi log-sources disable <id> # Pause ingestion"]).build(),delete:frA,remove:frA,skill:L("skill","Show setup skill for a log source provider",U7A).withOptions({...z,provider:{type:"string",description:"Log source provider (required)"}}).withExamples(["sazabi log-sources skill --provider gcp # Show GCP setup skill","sazabi log-sources skill --provider fly_io # Show Fly.io setup skill"]).build()}).withExamples(["sazabi log-sources providers # List available providers","sazabi log-sources list # List log sources","sazabi log-sources create otel # Connectionless: mints a keyed endpoint",`sazabi log-sources create fly_io --metadata '{"apiToken":"..."}' # Managed: connects with credentials`,"sazabi log-sources skill --provider gcp # Show agent setup skill"]).build();iA();iA();$Q();pr();uA();import*as Mi from"node:fs";import*as _b from"node:readline";var Qa=(A)=>new Promise((t)=>setTimeout(t,A));var L7A=(A)=>{return`${A.getTime()*1e6}`},S7A=(A)=>Object.entries(A).map(([t,g])=>({key:t,value:{stringValue:g}})),F7A=[{pattern:/\b(?:fatal|critical|crit)\b/i,severityNumber:21,severityText:"FATAL"},{pattern:/\b(?:error|err)\b/i,severityNumber:17,severityText:"ERROR"},{pattern:/\b(?:warn|warning)\b/i,severityNumber:13,severityText:"WARN"},{pattern:/\bdebug\b/i,severityNumber:5,severityText:"DEBUG"},{pattern:/\btrace\b/i,severityNumber:1,severityText:"TRACE"}],M7A={severityNumber:9,severityText:"INFO"},k7A=(A)=>{let t=null;for(let{pattern:g,severityNumber:i,severityText:n}of F7A){let o=g.exec(A);if(o&&(t===null||o.index<t.index))t={index:o.index,severityNumber:i,severityText:n}}return t?{severityNumber:t.severityNumber,severityText:t.severityText}:M7A},zrA=(A,t,g={})=>{let n=L7A(new Date),o=g.serviceName??"sazabi-cli",e=S7A(g.attributes??{}),I=A.filter((h)=>h.trim().length>0).map((h)=>({timeUnixNano:n,observedTimeUnixNano:n,...k7A(h),body:{stringValue:h},attributes:e}));return{resourceLogs:[{resource:{attributes:[{key:"service.name",value:{stringValue:o}},{key:"sazabi.public_key",value:{stringValue:t}}]},scopeLogs:[{scope:{name:"sazabi-cli-forward",version:"1.0.0"},logRecords:I}]}]}};function Y7A(A,t,g){return A===1?t:g??`${t}s`}function In(A,t,g){return`${A} ${Y7A(A,t,g)}`}CA();Yn();var $7A="15003",G7A="SAZABI_INTERNAL_LOG_FORWARDING_SECRET",T7A="SAZABI_INTERNAL_LOG_FORWARDING_SOURCE",J7A="sazabi.source",P7A="sazabi.internal.source",R7A=(A)=>{return A.startsWith("[")&&A.endsWith("]")?A.slice(1,-1):A},f7A=(A)=>{let t=R7A(A);return t==="localhost"||t==="127.0.0.1"||t==="::1"},v7A=(A)=>{let t=(()=>{try{return new URL(A)}catch{return null}})();if(!t)return;if(!f7A(t.hostname))return;return t.protocol="http:",t.port=$7A,t.pathname="",t.search="",t.hash="",t.toString()},O7A=async(A,t)=>{if(!t)IA("Ensuring public key exists...");let g=await A.publicKeys.ensureLogForwarding({});if(!g.success){if(!t)Gn(`Failed to ensure public key: ${g.error}. Pass --public-key <value> or check your project access and try again.`);return null}if(!t)x(`Using public key: ${g.value.publicKey.name}`);return{value:g.value.publicKey.value,projectId:g.value.publicKey.projectId,createdAt:g.value.publicKey.createdAt}},z7A=({explicitPublicKey:A,cachedPublicKey:t,cachedPublicKeyProjectId:g,activeProjectId:i})=>{let n=A?.trim();if(n)return n;let o=t?.trim();if(!o)return;return g?.trim()===i?o:void 0},m7A=(A)=>{if(!A||A.length===0)return{success:!0,value:{}};let t={};for(let g of A){let i=g.indexOf("=");if(i<=0)return{success:!1,error:`Invalid attribute "${g}". Use key=value.`};let n=g.slice(0,i).trim();if(!n)return{success:!1,error:`Invalid attribute "${g}". Attribute key is required.`};t[n]=g.slice(i+1)}return{success:!0,value:t}},W7A=(A)=>{let t=process.env[G7A]?.trim();if(!t)return;let g=process.env[T7A]?.trim()||A[P7A]?.trim()||A[J7A]?.trim()||void 0;return{secret:t,...g?{source:g}:{}}},wv=(A,t,g,i,n,o,e,I,h,B,c)=>{return async()=>{if(A.length===0)return;let C=zrA(A,i,I),r=H7A(C);if(A.length=0,r===0)return;if(!B)IA(`Forwarding ${In(r,"log")}...`);let a=await g.logs.forward({publicKey:i,logs:C,region:o,...e?{projectId:e}:{},...h?{sazabiInternalForwarding:h}:{}});while(!a.success&&s7A(a)&&x7A(n)){if(!B)IA("Public key is still propagating to intake (usually under a minute); retrying...");await Qa(_7A),a=await g.logs.forward({publicKey:i,logs:C,region:o,...e?{projectId:e}:{},...h?{sazabiInternalForwarding:h}:{}})}if(!a.success){if(X7A(a)){l(a,"Failed to forward logs",B);return}if(t.totalFailed+=r,!B)jg(`Failed to forward logs: ${a.error}`);c?.({forwarded:0,failed:r});return}t.totalForwarded+=a.value.forwardedCount,t.totalFailed+=a.value.failedCount,c?.({forwarded:a.value.forwardedCount,failed:a.value.failedCount})}},Z7A=async(A,t,g,i,n,o,e,I,h,B,c)=>{let C=Mi.createReadStream(A),r=_b.createInterface({input:C,crlfDelay:Number.POSITIVE_INFINITY}),a=[],y={totalForwarded:0,totalFailed:0},w=wv(a,y,t,g,i,n,o,e,I,B,(b)=>c?.push(b));try{for await(let b of r)if(a.push(b),a.length>=h)await w()}catch(b){Gn(`Couldn't read ${A} (check that the file exists and is readable): ${b instanceof Error?b.message:String(b)}`);return}if(await w(),B);else if(MA(),Gi(jA.muted("─".repeat(80))),x(`Forwarded ${In(y.totalForwarded,"log")}.`),y.totalFailed>0)jg(`Failed to forward ${In(y.totalFailed,"log")}.`)},V7A=async(A,t,g,i,n,o,e,I,h,B)=>{let c=_b.createInterface({input:process.stdin,output:process.stdout,terminal:!1}),C=[],r={totalForwarded:0,totalFailed:0},a=wv(C,r,A,t,g,i,n,o,e,h,(y)=>B?.push(y));try{for await(let y of c)if(C.push(y),C.length>=I)await a()}catch(y){Gn(`Couldn't read from stdin (check the input stream and try again): ${y instanceof Error?y.message:String(y)}`);return}if(await a(),h);else if(MA(),Gi(jA.muted("─".repeat(80))),x(`Forwarded ${In(r.totalForwarded,"log")}.`),r.totalFailed>0)jg(`Failed to forward ${In(r.totalFailed,"log")}.`)},j7A=async(A,t,g,i,n,o,e,I,h,B,c)=>{let C=[],r={totalForwarded:0,totalFailed:0},a=wv(C,r,t,g,i,n,o,e,I,B,(oA)=>c?.push(oA)),y=null,w=null,b=async()=>{if(w)clearTimeout(w);if(y)y.close();if(await a(),B);else if(MA(),Gi(jA.muted("─".repeat(80))),x(`Forwarded ${In(r.totalForwarded,"log")}.`),r.totalFailed>0)jg(`Failed to forward ${In(r.totalFailed,"log")}.`)};process.on("SIGINT",async()=>{MA(),IA("Interrupted, flushing remaining logs..."),await b(),process.exit(0)});let N=null,k=null,T=!1,V=0,P=async()=>{if(T)return;T=!0;try{if((await Mi.promises.stat(A)).size<V)V=0;N=Mi.createReadStream(A,{encoding:"utf8",start:V}),k=_b.createInterface({input:N,crlfDelay:Number.POSITIVE_INFINITY});for await(let bA of k)if(C.push(bA),C.length>=h)await a();V=(await Mi.promises.stat(A)).size}catch(oA){Gn(`Couldn't read ${A} (check that the file exists and is readable): ${oA instanceof Error?oA.message:String(oA)}`)}finally{T=!1}};await P(),y=Mi.watch(A,async(oA)=>{if(oA==="change"){if(w)clearTimeout(w);w=setTimeout(async()=>{if(T)return;if(N)N.close();if(k)k.close();await Qa(50),await P()},100)}})},mrA=async(A)=>{let t=A.batchSize??100;if(t<=0){if(A.json)return u("Batch size must be a positive number.");throw D("Batch size must be a positive number."),Error("Unreachable")}let g=l(m7A(A.attributes),"Invalid --attribute value",A.json===!0);if(A.follow&&!A.file){if(A.json)return u("--follow requires --file to be specified.");throw D("--follow requires --file to be specified."),Error("Unreachable")}let i=(()=>{let T=yt();if(!T.success)throw D(`Couldn't read settings (check that ~/.sazabi/settings.json is readable): ${T.error}`),Error("Unreachable");return T.value})(),n=l(on(i),"Couldn't resolve profile (run 'sazabi profiles list' to see available profiles)"),o=A.json===!0,e=R({tokenFlag:A.token,jsonMode:o}),I=Fi({cliFlag:A.apiBaseUrl,globalUrl:n.apiBaseUrl,globalDomain:n.apiDomain,buildUrlFromDomain:(T)=>`https://api.${T}`,defaultUrl:"https://api.sazabi.com"});if(!o)JA("Forwarding logs");let h=await fb({token:e.token,projectId:e.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:o});if(!o)IA(`Project: ${h.name}`);let B;if(A.region)B=q7A(A.region,o);else B=h.region;if(!o)IA(`Region: ${B}`);if(!o)IA(`Batch size: ${t}`);let c={serviceName:A.service?.trim()||void 0,attributes:g},C=W7A(g),r=A.intakeBaseUrl??n.intakeBaseUrl??v7A(I)??(n.intakeDomain?fCA(n.intakeDomain,B):void 0)??`https://otlp.${B}.intake.sazabi.com`;try{let T=new URL(r);if(!o&&/\.intake\.sazabi\.(dev|com)$/.test(T.host)&&!T.host.startsWith("otlp."))jg("Intake base URL may not be the OTLP endpoint. For Sazabi, prefer https://otlp.{region}.intake.sazabi.dev or .com as appropriate.")}catch{}let a=qi({token:e.token,projectId:e.projectId,baseUrl:I,intakeBaseUrl:r}),y=z7A({explicitPublicKey:A.publicKey,cachedPublicKey:n.forwardPublicKey,cachedPublicKeyProjectId:n.forwardPublicKeyProjectId,activeProjectId:h.id}),w;if(!y){let T=await O7A(a,o);if(!T)throw D("Failed to ensure public key. Pass --public-key <value> or check your project access and try again."),Error("Unreachable");y=T.value;let V=Date.parse(T.createdAt);w=Number.isFinite(V)?V:void 0;let P=en(i,{forwardPublicKey:y,forwardPublicKeyProjectId:T.projectId});if(P.success){let oA=Ht(P.value);if(!oA.success)jg(`Failed to store public key: ${oA.error}`)}}if(!o)MA(),Gi(jA.muted("─".repeat(80))),MA();let b=!A.follow,N=[],k={forwarded:0,failed:0};if(A.follow&&A.file)await j7A(A.file,a,y,w,B,e.projectId,c,C,t,o,b?N:void 0);else if(A.file)await Z7A(A.file,a,y,w,B,e.projectId,c,C,t,o,N);else await V7A(a,y,w,B,e.projectId,c,C,t,o,N);for(let T of N)k.forwarded+=T.forwarded,k.failed+=T.failed;if(o){let T={forwardedCount:k.forwarded,failedCount:k.failed,batches:N,project:{id:h.id,name:h.name,region:B},intakeBaseUrl:r,batchSize:t,follow:Boolean(A.follow),file:A.file??void 0};console.log(JSON.stringify(T))}},H7A=(A)=>{return A.resourceLogs?.reduce((t,g)=>t+(g.scopeLogs?.reduce((i,n)=>i+(n.logRecords?.length??0),0)??0),0)??0},X7A=(A)=>{if(A.success)return!1;if(A.errorPayload)return!0;if(A.statusCode!==void 0&&A.statusCode<500)return!0;return A.error.startsWith("Authentication failed")||A.error.startsWith("Client error (")},K7A=120000,_7A=5000,s7A=(A)=>!A.success&&(A.statusCode===401||A.statusCode===403||A.error.startsWith("Authentication failed")),x7A=(A,t=Date.now())=>A!==void 0&&Number.isFinite(A)&&t-A<K7A,q7A=(A,t)=>{let g=uB.safeParse(A);if(g.success)return g.data;let i=`Invalid region: ${A}. Valid regions: ${uB.options.join(", ")}.`;if(t)return u(i);return D(i)};iA();uA();CA();import{readFile as d7A}from"node:fs/promises";var p7A={result:{label:"Result",type:{kind:"string"}},format:{label:"Format",type:{kind:"string"}},meta:{label:"Meta",type:{kind:"custom",render:(A)=>JSON.stringify(A),serialize:(A)=>A}}},AqA={layout:"field-list",schema:p7A,fields:["result","format","meta"]},WrA=async(A)=>{if(!A.query&&!A.file){if(A.json)return u("Pass --query or --file.");return D("Pass --query or --file.")}if(A.query&&A.file){if(A.json)return u("Pass either --query or --file, not both.");return D("Pass either --query or --file, not both.")}let t;if(A.query!==void 0)t=A.query;else try{t=await d7A(A.file,"utf8")}catch(o){let e=`Couldn't read query file (check that the path exists and is readable): ${o instanceof Error?o.message:String(o)}`;if(A.json)return u(e);return D(e)}if(t.trim().length===0){if(A.json)return u("Query cannot be empty.");return D("Query cannot be empty.")}let g=R({tokenFlag:A.token,projectIdFlag:A.project,jsonMode:A.json}),i=f({token:g.token,projectId:g.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:A.json}),n=l(await i.logs.nativeQuery({query:t}),"Couldn't run native log query (check the query syntax and try again)",A.json);if(A.json){W(AqA,n,{json:!0});return}IA(`Backend ${n.meta.backendId} returned ${n.result.length} characters in ${n.meta.took}ms${n.meta.truncated?" (truncated)":""}`),process.stdout.write(n.result.endsWith(`
8752
+ ${U3A(g)}`:"";if(!A){let o=`--credentials is required for ${t} (JSON object).${n}`;if(i)u(o);else D(o);return}try{let o=JSON.parse(A);if(typeof o!=="object"||o===null||Array.isArray(o))throw Error("not an object");return o}catch{let o=`--credentials must be a JSON object, e.g. '{"apiToken":"..."}'.${n}`;if(i)u(o);else D(o);return}},L3A=async(A)=>{let{values:t,positionals:g}=F(A,{...m,credentials:{type:"string"},"display-name":{type:"string"},project:{type:"string"}},{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return u("Provider is required.");return D("Provider is required. Run 'sazabi integrations providers' to see options.")}let{client:o}=GB(t),{providers:e}=l(await o.integrations.listProviders(),"Couldn't load the integration provider catalog (try again)",n),I=e.find((r)=>r.id===i);if(!I){let r=e.map((y)=>y.id).join(", "),a=`Unknown integration provider "${i}". Available: ${r}`;if(n)return u(a);return D(a)}let h=t["display-name"];if(I.authType==="api_key"){let r=DrA(t.credentials,I.name,I.credentialFields??[],n);if(!r)return;let{connection:a}=l(await o.integrations.createConnection({provider:i,displayName:h,credentials:r}),`Couldn't connect ${I.name} (check the credentials and try again)`,n);if(!n)x(`Connected ${I.name}.`);W(jb,a,{json:n});return}if(!I.browserConnectSupported){let r=`${I.name} can't be connected from the CLI yet. Connect it from the dashboard integration settings.`;if(n)return u(r);return D(r)}if(t.credentials){let r=`${I.name} connects through a browser flow — --credentials does not apply.`;if(n)return u(r);return D(r)}let B=l(await o.integrations.beginConnect({provider:i,displayName:h,projectId:t.project}),`Couldn't start the ${I.name} connect flow`,n);if(!n)JA(`Connect ${I.name}`),IA("Complete the authorization in a browser where you're signed in to the Sazabi dashboard as the same user."),IA(`Opening ${jA.info(B.url)}`);if(YB(B.url),!n)IA("Waiting for the browser flow to complete...");let c=new Date(B.expiresAt).getTime()+15000;while(Date.now()<c){await $B(N3A);let r=l(await o.integrations.getConnectAttempt(B.attemptId),"Couldn't poll the connect attempt (try again)",n);if(r.status==="pending")continue;if(r.status==="completed"&&r.connection){if(!n)x(`Connected ${I.name}.`);W(jb,r.connection,{json:n});return}if(r.status==="failed"){let a=r.errorCode??"unknown",y=yrA[a],w=y?`Connect did not complete (${a}). ${y}`:`Connect failed (${a}). Run the command again.`;if(n)return u(w);return D(w)}if(r.status==="not_connected"){let a=r.errorCode??void 0,w=(a?yrA[a]:void 0)??"Not connected yet — the flow finished but the connection isn't live (it may be awaiting approval). It'll appear once approved.";if(n){X({status:"not_connected",...a?{reason:a}:{},message:w});return}IA(w);return}break}let C="The browser flow didn't complete in time. Run the command again.";if(n)return u(C);return D(C)},S3A=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return u("Connection ID is required.");return D("Connection ID is required. Run 'sazabi integrations list' to see connection IDs.")}let{client:o}=GB(t);if(l(await o.integrations.disconnectConnection(i),"Couldn't disconnect the integration connection",n),n){X({success:!0});return}x("Integration connection disconnected.")},F3A=async(A)=>{let{values:t,positionals:g}=F(A,{...m,credentials:{type:"string"}},{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return u("Connection ID is required.");return D("Connection ID is required. Run 'sazabi integrations list' to see connection IDs.")}let o=DrA(t.credentials,"this connection",[],n);if(!o)return;let{client:e}=GB(t),{connection:I}=l(await e.integrations.updateConnectionCredentials({connectionId:i,credentials:o}),"Couldn't update the connection credentials (check the values and try again)",n);if(!n)x("Connection credentials updated.");W(jb,I,{json:n})},urA=nA("integrations","Connect and inspect integrations").withSubcommands({providers:L("providers","List supported integration providers",b3A).withOptions(z).withExamples(["sazabi integrations providers # List providers and connection counts","sazabi integrations providers --json # Machine-readable output"]).build(),connect:L("connect","Connect an integration (API-key credentials or a browser flow)",L3A).withPositionalArgs("<provider>").withOptions({...z,credentials:{type:"string",description:'Vendor credentials as JSON for api_key providers, e.g. \'{"apiToken":"..."}\' (see credentialFields in `integrations providers --json`)'},"display-name":{type:"string",description:"Optional display name for the connection"},project:{type:"string",description:"Project the completed connection defaults its routing to (browser flows)"}}).withExamples([`sazabi integrations connect pagerduty --credentials '{"apiToken":"..."}' # API-key connect`,"sazabi integrations connect jira # Browser OAuth connect","sazabi integrations connect github # GitHub App install"]).build(),disconnect:L("disconnect","Disconnect an integration connection",S3A).withPositionalArgs("<connection-id>").withOptions(z).withExamples(["sazabi integrations disconnect <connection-id> # Soft-delete the connection"]).build(),"update-credentials":L("update-credentials","Replace an api_key connection's credentials (reconnect path)",F3A).withPositionalArgs("<connection-id>").withOptions({...z,credentials:{type:"string",description:"Replacement vendor credentials as JSON"}}).withExamples([`sazabi integrations update-credentials <connection-id> --credentials '{"apiToken":"..."}' # Replace stored credentials`]).build(),list:L("list","List integration connections for the organization",l3A).withOptions({...z,provider:{type:"string",description:"Filter by provider (e.g. slack, github, pagerduty)"}}).withExamples(["sazabi integrations list # All connections","sazabi integrations list --provider slack # Filter by provider"]).build(),get:L("get","Get one integration connection by ID",ErA).withPositionalArgs("<connection-id>").withOptions(z).withExamples(["sazabi integrations get <connection-id> # Connection detail"]).build(),details:L("details","Show details for one integration connection",ErA).withPositionalArgs("<connection-id>").withOptions(z).withExamples(["sazabi integrations details <connection-id> # Connection detail"]).build()}).withExamples(["sazabi integrations providers # List providers","sazabi integrations connect pagerduty --credentials '{...}' # Connect an integration","sazabi integrations list # List connections","sazabi integrations get <connection-id> # Connection detail"]).build();iA();$Q();import{readFile as M3A}from"node:fs/promises";uA();CA();var Cv={id:{label:"ID",type:{kind:"string"}},projectId:{label:"Project",type:{kind:"string"}},url:{label:"URL",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},status:{label:"Status",type:{kind:"string"}},severity:{label:"Severity",type:{kind:"severity"}},componentId:{label:"Component",type:{kind:"nullable-string"}},createdAt:{label:"Created",type:{kind:"date"}},resolvedAt:{label:"Resolved",type:{kind:"nullable-date"}},mutedAt:{label:"Muted",type:{kind:"nullable-date"}},muteHitCount:{label:"Mute hits",type:{kind:"number"}},lastActivityAt:{label:"Last activity",type:{kind:"nullable-date"}},lastDeliveredAt:{label:"Last delivered",type:{kind:"nullable-date"}},description:{label:"Description",type:{kind:"nullable-string"}},delivery:{label:"Delivery",type:{kind:"custom",render:(A)=>A==null?"(none)":JSON.stringify(A,null,2),serialize:(A)=>A??null}}},k3A={...Cv,duplicateIssueId:{label:"Reused issue",type:{kind:"nullable-string"}}},brA=["id","projectId","url","name","status","severity","componentId","createdAt","resolvedAt","mutedAt","muteHitCount","lastActivityAt","lastDeliveredAt","description"],lrA={schema:Cv,columns:["id","name","status","severity","createdAt","mutedAt","url"],jsonFields:brA,header:"Issues",emptyMessage:"No issues found."},Y3A={...lrA,jsonFields:[...brA,"delivery"]},Ie={layout:"sections",schema:Cv,primary:{title:"Issue",fields:["id","url","name","status","severity","createdAt","resolvedAt","mutedAt","muteHitCount","lastActivityAt","lastDeliveredAt","componentId"]},secondary:[{title:"Description",field:"description"}]},he=(A)=>({...A,url:$CA(A.projectId,A.id)}),$3A={...Ie,schema:k3A,secondary:[{title:"Reused existing issue",field:"duplicateIssueId"},...Ie.secondary??[]]},G3A={layout:"field-list",title:"Issue counts",schema:{total:{label:"Total",type:{kind:"number"}},byStatus:{label:"By status",type:{kind:"custom",render:(A)=>JSON.stringify(A),serialize:(A)=>A}},bySeverity:{label:"By severity",type:{kind:"custom",render:(A)=>JSON.stringify(A),serialize:(A)=>A}},filters:{label:"Filters",type:{kind:"custom",render:(A)=>JSON.stringify(A),serialize:(A)=>A},get:(A)=>A.filters}},fields:["total","byStatus","bySeverity","filters"]},T3A=fy.partial(),J3A={contentMdx:"contentMdx cannot be empty. Provide the issue body via --content-mdx or the contentMdx field in --from-json.",componentId:"componentId is required. Run `sazabi components list --json`, pick the matching component, and pass --component <id> (or componentId in --from-json)."},P3A=async(A)=>{let t=await j3A(A);if(!t.ok){if(A.json)return u(t.message);return D(t.message)}let g=R({tokenFlag:A.token,jsonMode:A.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),n=l(await i.issues.create(t.input),"Failed to create issue",A.json);W($3A,{...n.issue,duplicateIssueId:n.duplicateIssueId??null},{json:A.json})},R3A=async(A)=>{let t=R({tokenFlag:A.token,jsonMode:A.json}),g=f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=l(await g.issues.list({status:A.status,severity:A.severity,componentId:A.componentId,limit:A.limit,cursor:A.cursor}),"Couldn't list issues (check the active project and try again)",A.json);s(lrA,i.issues.map(he),{json:A.json,nextCursor:i.nextCursor})},f3A=async(A)=>{let t=R({tokenFlag:A.token,jsonMode:A.json}),g=f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=l(await g.issues.search({name:A.name,status:A.status,severity:A.severity,componentId:A.componentId,limit:A.limit,cursor:A.cursor,includeDeliveryMetadata:A.includeDeliveryMetadata}),"Couldn't search issues (check the active project and try again)",A.json);s(Y3A,i.issues.map(he),{json:A.json,nextCursor:i.nextCursor})},v3A=async(A)=>{let t=R({tokenFlag:A.token,jsonMode:A.json}),g=f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=l(await g.issues.count({name:A.name,status:A.status,severity:A.severity,componentId:A.componentId}),"Couldn't count issues (check the active project and try again)",A.json);W(G3A,i,{json:A.json})},O3A=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.issues.get(A),"Couldn't get issue (run 'sazabi issues list' to see issue IDs)",t.json);W(Ie,he(n.issue),{json:t.json})},z3A=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.issues.resolve(A),"Failed to resolve issue",t.json);W(Ie,he(n.issue),{json:t.json})},m3A=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.issues.reopen(A),"Failed to reopen issue",t.json);W(Ie,he(n.issue),{json:t.json})},W3A=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.issues.ignore(A),"Failed to ignore issue",t.json);W(Ie,he(n.issue),{json:t.json})},Z3A=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.issues.mute(A),"Failed to mute issue",t.json);W(Ie,he(n.issue),{json:t.json})},V3A=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.issues.unmute(A),"Failed to unmute issue",t.json);W(Ie,he(n.issue),{json:t.json})},j3A=async(A)=>{let t=A.fromJson?await H3A(A.fromJson):{ok:!0,input:{}};if(!t.ok)return t;let g={...t.input,...A.name!==void 0?{name:A.name}:{},...A.contentMdx!==void 0?{contentMdx:A.contentMdx}:{},...A.severity!==void 0?{severity:A.severity}:{},...A.componentId!==void 0?{componentId:A.componentId}:{}},i=vy.safeParse(g);if(!i.success)return{ok:!1,message:NrA(i.error)};return{ok:!0,input:i.data}},H3A=async(A)=>{let t;try{t=A==="-"?await X3A():await M3A(A,"utf8")}catch(n){return{ok:!1,message:`Couldn't read issue input (check that the --from-json path exists and is readable): ${n instanceof Error?n.message:String(n)}`}}let g;try{g=JSON.parse(t)}catch(n){return{ok:!1,message:`Couldn't parse issue input JSON (fix the JSON syntax and try again): ${n instanceof Error?n.message:String(n)}`}}let i=T3A.safeParse(g);if(!i.success)return{ok:!1,message:NrA(i.error)};return{ok:!0,input:i.data}},X3A=async()=>{let A=[];process.stdin.setEncoding("utf8");for await(let t of process.stdin)A.push(String(t));return A.join("")},NrA=(A)=>{let t=A.issues[0];if(!t)return"Invalid issue input.";let g=t.path[0];if(g&&t.code==="invalid_type")return J3A[g]??t.message;return t.message},UrA=nA("issues","Manage issues").withSubcommands({create:L("create","Create an issue, reusing an existing open issue when one matches",async(A)=>{let{values:t}=F(A,{...m,name:{type:"string"},"content-mdx":{type:"string"},severity:{type:"string"},component:{type:"string"},"from-json":{type:"string"}});await P3A({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],name:t.name,contentMdx:t["content-mdx"],severity:t.severity,componentId:t.component,fromJson:t["from-json"]})}).withOptions({...z,name:{type:"string",description:"Stable issue name for indexing and mute matching"},"content-mdx":{type:"string",description:"Safe Sazabi MDX document for the issue body (impact, root cause, remediation, evidence)"},severity:{type:"string",description:"Issue severity: low, medium, high, or critical (default: medium)"},component:{type:"string",description:"Required component ID. List with `sazabi components list` first; register one if none fits"},"from-json":{type:"string",description:"Read issue fields from a JSON file, or '-' for stdin"}}).withExamples(['sazabi issues create --content-mdx "Checkout is returning 500s due to pool exhaustion." --component "$COMPONENT_ID" # Create an issue from MDX content',"sazabi issues create --from-json issue.json # Create an issue from a JSON file with contentMdx","cat issue.json | sazabi issues create --from-json - --json # Create an issue from stdin"]).build(),list:L("list","List issues in the active project",async(A)=>{let{values:t}=F(A,{...m,status:{type:"string"},severity:{type:"string"},component:{type:"string"},limit:{type:"string"},cursor:{type:"string"}}),g=["open","resolved","ignored"];if(t.status&&!g.includes(t.status)){let o=`Invalid --status "${t.status}". Must be one of: ${g.join(", ")}.`;if(t.json)return u(o);return D(o)}let i=["low","medium","high","critical"];if(t.severity&&!i.includes(t.severity)){let o=`Invalid --severity "${t.severity}". Must be one of: ${i.join(", ")}.`;if(t.json)return u(o);return D(o)}let n=t.limit?Number(t.limit):void 0;if(n!==void 0&&(Number.isNaN(n)||n<1||n>100)){if(t.json)return u("Invalid --limit. Must be an integer between 1 and 100.");return D("Invalid --limit. Must be an integer between 1 and 100.")}await R3A({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],status:t.status,severity:t.severity,componentId:t.component,limit:n,cursor:t.cursor})}).withOptions({...z,status:{type:"string",description:"Filter by status: open, resolved, or ignored"},severity:{type:"string",description:"Filter by severity: low, medium, high, or critical"},component:{type:"string",description:"Filter by component ID"},limit:{type:"string",description:"Maximum number of issues to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from previous response"}}).withExamples(["sazabi issues list # List all issues","sazabi issues list --status open # List open issues only","sazabi issues list --component <component-id> # List issues for a component"]).build(),search:L("search","Search issues by name and filters",async(A)=>{let{values:t,positionals:g}=F(A,{...m,name:{type:"string"},status:{type:"string"},severity:{type:"string"},component:{type:"string"},limit:{type:"string"},cursor:{type:"string"},"include-delivery-metadata":{type:"boolean"}},{allowPositionals:!0}),i=["open","resolved","ignored"];if(t.status&&!i.includes(t.status)){let I=`Invalid --status "${t.status}". Must be one of: ${i.join(", ")}.`;if(t.json)return u(I);return D(I)}let n=["low","medium","high","critical"];if(t.severity&&!n.includes(t.severity)){let I=`Invalid --severity "${t.severity}". Must be one of: ${n.join(", ")}.`;if(t.json)return u(I);return D(I)}let o=t.limit?Number(t.limit):void 0;if(o!==void 0&&(Number.isNaN(o)||o<1||o>100)){if(t.json)return u("Invalid --limit. Must be an integer between 1 and 100.");return D("Invalid --limit. Must be an integer between 1 and 100.")}let e=g.join(" ").trim();await f3A({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],name:t.name??(e||void 0),status:t.status,severity:t.severity,componentId:t.component,limit:o,cursor:t.cursor,includeDeliveryMetadata:t["include-delivery-metadata"]})}).withPositionalArgs("[name]").withOptions({...z,name:{type:"string",description:"Case-insensitive partial issue name match"},status:{type:"string",description:"Filter by status: open, resolved, or ignored"},severity:{type:"string",description:"Filter by severity: low, medium, high, or critical"},component:{type:"string",description:"Filter by component ID"},limit:{type:"string",description:"Maximum number of issues to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from previous response"},"include-delivery-metadata":{type:"boolean",description:"Include delivery metadata in JSON output"}}).withExamples(['sazabi issues search "checkout" --status open # Search open issues by name',"sazabi issues search --severity critical --json # Machine-readable search"]).build(),count:L("count","Count issues by status and severity",async(A)=>{let{values:t,positionals:g}=F(A,{...m,name:{type:"string"},status:{type:"string"},severity:{type:"string"},component:{type:"string"}},{allowPositionals:!0}),i=["open","resolved","ignored"];if(t.status&&!i.includes(t.status)){let e=`Invalid --status "${t.status}". Must be one of: ${i.join(", ")}.`;if(t.json)return u(e);return D(e)}let n=["low","medium","high","critical"];if(t.severity&&!n.includes(t.severity)){let e=`Invalid --severity "${t.severity}". Must be one of: ${n.join(", ")}.`;if(t.json)return u(e);return D(e)}let o=g.join(" ").trim();await v3A({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],name:t.name??(o||void 0),status:t.status,severity:t.severity,componentId:t.component})}).withPositionalArgs("[name]").withOptions({...z,name:{type:"string",description:"Case-insensitive partial issue name match"},status:{type:"string",description:"Filter by status: open, resolved, or ignored"},severity:{type:"string",description:"Filter by severity: low, medium, high, or critical"},component:{type:"string",description:"Filter by component ID"}}).withExamples(["sazabi issues count --status open # Count open issues",'sazabi issues count "checkout" --json # Count matching issues']).build(),get:L("get","Get one issue by ID",async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Issue ID is required.");return D("Issue ID is required.")}await O3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<issue-id>").withOptions(z).withExamples(["sazabi issues get <issue-id> # Get one issue"]).build(),resolve:L("resolve","Resolve an open issue",async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Issue ID is required.");return D("Issue ID is required.")}await z3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<issue-id>").withOptions(z).withExamples(["sazabi issues resolve <issue-id> # Resolve an issue"]).build(),ignore:L("ignore","Ignore an issue",async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Issue ID is required.");return D("Issue ID is required.")}await W3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<issue-id>").withOptions(z).withExamples(["sazabi issues ignore <issue-id> # Ignore an issue"]).build(),reopen:L("reopen","Reopen a resolved or ignored issue",async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Issue ID is required.");return D("Issue ID is required.")}await m3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<issue-id>").withOptions(z).withExamples(["sazabi issues reopen <issue-id> # Reopen a resolved or ignored issue"]).build(),mute:L("mute","Mute an issue",async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Issue ID is required.");return D("Issue ID is required.")}await Z3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<issue-id>").withOptions(z).withExamples(["sazabi issues mute <issue-id> # Mute an issue"]).build(),unmute:L("unmute","Unmute an issue",async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Issue ID is required.");return D("Issue ID is required.")}await V3A(i,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<issue-id>").withOptions(z).withExamples(["sazabi issues unmute <issue-id> # Unmute an issue"]).build()}).withExamples(["sazabi issues create --from-json issue.json # Create an issue","sazabi issues list # List all issues","sazabi issues search checkout # Search issues","sazabi issues count --status open # Count issues","sazabi issues get <issue-id> # Get one issue","sazabi issues resolve <issue-id> # Resolve an issue","sazabi issues ignore <issue-id> # Ignore an issue","sazabi issues mute <issue-id> # Mute an issue","sazabi issues unmute <issue-id> # Unmute an issue"]).build();iA();uA();CA();var K3A=async(A,t)=>{let g=R({tokenFlag:t.token,projectIdFlag:A==="public"?t.projectId:void 0,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:A==="public"?g.projectId:void 0,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json});if(A==="public"){let o=l(await i.publicKeys.list({projectId:g.projectId,limit:t.limit,cursor:t.cursor}),"Couldn't list public keys (check the active project and try again)",t.json);s(LrA(A),o.publicKeys.map((e)=>Be(A,e)),{json:t.json,nextCursor:o.nextCursor});return}let n=l(await i.secretKeys.list({limit:t.limit,cursor:t.cursor}),"Couldn't list secret keys (check your organization access and try again)",t.json);s(LrA(A),n.secretKeys.map((o)=>Be(A,o)),{json:t.json,nextCursor:n.nextCursor})},_3A=async(A,t,g)=>{let i=R({tokenFlag:g.token,projectIdFlag:A==="public"?g.projectId:void 0,jsonMode:g.json}),n=f({token:i.token,organizationId:i.organizationId,projectId:A==="public"?i.projectId:void 0,apiBaseUrlFlag:g.apiBaseUrl,jsonMode:g.json});if(A==="public"){let e=l(await n.publicKeys.get(t,i.projectId),"Couldn't get public key (run 'sazabi public-keys list' to see key IDs)",g.json);W(TB(A),Be(A,e.publicKey),{json:g.json});return}let o=l(await n.secretKeys.get(t),"Couldn't get secret key (run 'sazabi secret-keys list' to see key IDs)",g.json);W(TB(A),Be(A,o.secretKey),{json:g.json})},s3A=async(A,t)=>{let i=R({tokenFlag:t.token,projectIdFlag:void 0,jsonMode:t.json}),n=f({token:i.token,organizationId:i.organizationId,projectId:void 0,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),o={name:A,...t.expiresAt?{expiresAt:t.expiresAt}:{}},e=l(await n.secretKeys.create(o),"Failed to create secret key",t.json);if(t.json){X(e);return}x(`Secret key ${e.secretKey.name} created.`),zA({Value:e.secretKey.value}),W(TB("secret"),{...Be("secret",e.secretKey)})},x3A=async(A,t,g)=>{if(g.name===void 0&&g.expiresAt===void 0&&!g.clearExpiresAt){if(g.json)return u("At least one update is required. Pass --name, --expires-at, or --clear-expires-at.");return D("At least one update is required. Pass --name, --expires-at, or --clear-expires-at.")}if(g.expiresAt&&g.clearExpiresAt){if(g.json)return u("Use either --expires-at or --clear-expires-at, not both.");return D("Use either --expires-at or --clear-expires-at, not both.")}let i=R({tokenFlag:g.token,projectIdFlag:A==="public"?g.projectId:void 0,jsonMode:g.json}),n=f({token:i.token,organizationId:i.organizationId,projectId:A==="public"?i.projectId:void 0,apiBaseUrlFlag:g.apiBaseUrl,jsonMode:g.json}),o=g.clearExpiresAt?null:g.expiresAt!==void 0?g.expiresAt:void 0;if(A==="public"){let h={projectId:i.projectId,keyId:t,...g.name!==void 0?{name:g.name}:{},...o!==void 0?{expiresAt:o}:{}},B=l(await n.publicKeys.update(h),"Failed to update public key",g.json);W(TB(A),Be(A,B.publicKey),{json:g.json});return}let e={keyId:t,...g.name!==void 0?{name:g.name}:{},...o!==void 0?{expiresAt:o}:{}},I=l(await n.secretKeys.update(e),"Failed to update secret key",g.json);W(TB(A),Be(A,I.secretKey),{json:g.json})},q3A=async(A,t)=>{let g=R({tokenFlag:t.token,projectIdFlag:t.projectId,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.publicKeys.deactivate({projectId:g.projectId,keyId:A}),"Failed to deactivate public key",t.json);if(!t.json)x(`Public key ${A} deactivated.`);W(TB("public"),Be("public",n.publicKey),{json:t.json})},d3A=async(A,t)=>{let g=R({tokenFlag:t.token,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json});if(l(await i.secretKeys.delete({keyId:A}),"Failed to delete secret key",t.json),t.json){X({deleted:!0,keyId:A});return}x(`Secret key ${A} deleted.`)},SrA=(A)=>{let t=p3A(A),g=rv(A),i=A==="secret",n=i?"the organization":"the active project",o={token:{type:"string"},"project-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},h=i?{token:{type:"string",description:"Override token"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}:{token:{type:"string",description:"Override token"},"project-id":{type:"string",description:"Override project selection"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}};return nA(t,`Manage ${A} keys`).withSubcommands({list:L("list",`List ${A} keys in ${n}`,async(B)=>{let{values:c,positionals:C}=F(B,{...o,limit:{type:"string"},cursor:{type:"string"}},{allowPositionals:!0});if(C.length>0){let r=C.join(", ");if(c.json)return u(`Unexpected arguments: ${r}.`);return D(`Unexpected arguments: ${r}.`)}await K3A(A,{token:c.token,projectId:c["project-id"],limit:c.limit?Number(c.limit):void 0,cursor:c.cursor,json:c.json,apiBaseUrl:c["api-base-url"]})}).withOptions({...h,limit:{type:"string",description:"Maximum number of keys to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from previous response"}}).withExamples([`sazabi ${t} list # List ${A} keys in ${n}`]).build(),get:L("get",`Get one ${A} key by ID`,async(B)=>{let{values:c,positionals:C}=F(B,o,{allowPositionals:!0}),r=C[0];if(!r){let a=`${g} key ID is required.`;if(c.json)return u(a);return D(a)}await _3A(A,r,{token:c.token,projectId:c["project-id"],json:c.json,apiBaseUrl:c["api-base-url"]})}).withPositionalArgs("<key-id>").withOptions(h).withExamples([`sazabi ${t} get <key-id> # Get one ${A} key`]).build(),...i?{create:L("create",`Create one ${A} key in ${n}`,async(B)=>{let{values:c,positionals:C}=F(B,{...o,"expires-at":{type:"string"}},{allowPositionals:!0}),r=C.join(" ");if(!r){let a=`${g} key name is required.`;if(c.json)return u(a);return D(a)}await s3A(r,{token:c.token,projectId:c["project-id"],expiresAt:c["expires-at"],json:c.json,apiBaseUrl:c["api-base-url"]})}).withPositionalArgs("<name>").withOptions({...h,"expires-at":{type:"string",description:"Optional ISO timestamp when the key should expire"}}).withExamples([`sazabi ${t} create "CI agent" # Create one ${A} key`]).build()}:{},update:L("update",`Update one ${A} key in ${n}`,async(B)=>{let{values:c,positionals:C}=F(B,{...o,name:{type:"string"},"expires-at":{type:"string"},"clear-expires-at":{type:"boolean"}},{allowPositionals:!0}),r=C[0];if(!r){let a=`${g} key ID is required.`;if(c.json)return u(a);return D(a)}await x3A(A,r,{token:c.token,projectId:c["project-id"],name:c.name,expiresAt:c["expires-at"],clearExpiresAt:c["clear-expires-at"],json:c.json,apiBaseUrl:c["api-base-url"]})}).withPositionalArgs("<key-id>").withOptions({...h,name:{type:"string",description:`New ${A} key name`},"expires-at":{type:"string",description:"New ISO timestamp when the key should expire"},"clear-expires-at":{type:"boolean",description:"Clear any configured expiration"}}).withExamples([`sazabi ${t} update <key-id> --name "Renamed key" # Update one ${A} key`]).build(),...A==="public"?{deactivate:L("deactivate",`Deactivate one public key in ${n}`,async(B)=>{let{values:c,positionals:C}=F(B,o,{allowPositionals:!0}),r=C[0];if(!r){if(c.json)return u("Public key ID is required.");return D("Public key ID is required.")}await q3A(r,{token:c.token,projectId:c["project-id"],json:c.json,apiBaseUrl:c["api-base-url"]})}).withPositionalArgs("<key-id>").withOptions(h).withExamples([`sazabi ${t} deactivate <key-id> # Deactivate one public key`]).build()}:{delete:L("delete",`Delete one secret key from ${n}`,async(B)=>{let{values:c,positionals:C}=F(B,o,{allowPositionals:!0}),r=C[0];if(!r){if(c.json)return u("Secret key ID is required.");return D("Secret key ID is required.")}await d3A(r,{token:c.token,json:c.json,apiBaseUrl:c["api-base-url"]})}).withPositionalArgs("<key-id>").withOptions(h).withExamples([`sazabi ${t} delete <key-id> # Delete one secret key`]).build()}}).withExamples([`sazabi ${t} list # List ${A} keys in ${n}`,...i?[`sazabi ${t} create "CI agent" # Create one ${A} key`]:[]]).build()},FrA={keyType:{label:"Type",type:{kind:"string"}},id:{label:"ID",type:{kind:"string"}},projectId:{label:"Project ID",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},status:{label:"Status",type:{kind:"string"}},expiresAt:{label:"Expires",type:{kind:"nullable-date"}},lastUsedAt:{label:"Last used",type:{kind:"nullable-date"}},createdAt:{label:"Created",type:{kind:"date"}}},LrA=(A)=>({schema:FrA,columns:A==="public"?["id","name","status","expiresAt","lastUsedAt","createdAt"]:["id","name","expiresAt","lastUsedAt","createdAt"],header:`${rv(A)} keys`,emptyMessage:`No ${A} keys found.`}),TB=(A)=>({layout:"field-list",schema:FrA,fields:A==="public"?["keyType","id","projectId","name","status","expiresAt","lastUsedAt","createdAt"]:["keyType","id","name","expiresAt","lastUsedAt","createdAt"]}),p3A=(A)=>{return A==="public"?"public-keys":"secret-keys"},rv=(A)=>{return A==="public"?"Public":"Secret"},Be=(A,t)=>{let g=A==="public"&&"deactivatedAt"in t&&t.deactivatedAt!==null;return{...t,keyType:`${rv(A)} key`,status:g?"Deactivated":"Active"}},MrA=SrA("public"),krA=SrA("secret");iA();uA();CA();var oa=(A)=>({id:A.id,projectId:A.projectId,name:A.name,expression:A.expression,enabled:A.enabled,compiledVersion:A.compiledVersion,linkedAutomationIds:A.linkedAutomationIds??[],createdAt:A.createdAt,updatedAt:A.updatedAt}),YrA={id:{label:"ID",type:{kind:"id"}},projectId:{label:"Project ID",type:{kind:"id"}},name:{label:"Name",type:{kind:"string"}},expression:{label:"Expression",type:{kind:"string"}},enabled:{label:"Enabled",type:{kind:"custom",render:(A)=>A?"Yes":"No",serialize:(A)=>A}},compiledVersion:{label:"Compiled version",type:{kind:"number"}},linkedAutomationIds:{label:"Linked automations",type:{kind:"custom",render:(A)=>Array.isArray(A)&&A.length>0?A.join(", "):"(none)",serialize:(A)=>A}},createdAt:{label:"Created at",type:{kind:"nullable-date"}},updatedAt:{label:"Updated at",type:{kind:"nullable-date"}}},A7A={schema:YrA,columns:["name","enabled","updatedAt"],jsonFields:["id","projectId","name","expression","enabled","compiledVersion","linkedAutomationIds","updatedAt"],header:"Log-match expressions",emptyMessage:"No log-match expressions found."},Hb={layout:"field-list",schema:YrA,fields:["id","projectId","name","expression","enabled","compiledVersion","linkedAutomationIds","createdAt","updatedAt"],title:"Log-match expression"},na={...z,"project-id":{type:"string",description:"Override active project ID"}},ia={...m,"project-id":{type:"string"}},ea=(A)=>{let t=R({tokenFlag:A.token,projectIdFlag:A.projectId,jsonMode:A.json});return{client:f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json})}},av=(A,t)=>{let g=A[0]?.trim();if(!g){if(t){u("Expression ID is required.");return}D("Expression ID is required.");return}return g},t7A=(A,t)=>{let g=A[0]?.trim();if(!g){if(t){u("Expression name is required.");return}D("Expression name is required.");return}return g},g7A=async(A)=>{let{client:t}=ea(A),g=l(await t.logMatchExpressions.list(),"Couldn't list log-match expressions",A.json);s(A7A,g.expressions.map(oa),{json:A.json})},n7A=async(A,t)=>{let{client:g}=ea(t),i=l(await g.logMatchExpressions.get(A),"Couldn't get log-match expression (run 'sazabi log-match-expressions list' to see IDs)",t.json);W(Hb,oa(i.expression),{json:t.json})},i7A=async(A,t)=>{if(!t.expression?.trim()){if(t.json){u("CEL expression is required. Pass --expression '<CEL>'.");return}D("CEL expression is required. Pass --expression '<CEL>'.");return}if(t.enabled===!0&&t.disabled===!0){if(t.json){u("Use either --enabled or --disabled, not both.");return}D("Use either --enabled or --disabled, not both.");return}let g=t.disabled===!0?!1:t.enabled===!0?!0:void 0,{client:i}=ea(t),n=l(await i.logMatchExpressions.create({name:A,expression:t.expression,...g!==void 0?{enabled:g}:{}}),"Couldn't create log-match expression",t.json);if(!t.json)x(`Log-match expression "${n.expression.name}" created.`);W(Hb,oa(n.expression),{json:t.json})},o7A=async(A,t)=>{if(t.name===void 0&&t.expression===void 0&&t.enable!==!0&&t.disable!==!0){if(t.json){u("Nothing to update. Provide --name, --expression, --enable, or --disable.");return}D("Nothing to update. Provide --name, --expression, --enable, or --disable.");return}if(t.enable===!0&&t.disable===!0){if(t.json){u("Use either --enable or --disable, not both.");return}D("Use either --enable or --disable, not both.");return}let g=t.disable===!0?!1:t.enable===!0?!0:void 0,{client:i}=ea(t),n=l(await i.logMatchExpressions.update(A,{...t.name!==void 0?{name:t.name}:{},...t.expression!==void 0?{expression:t.expression}:{},...g!==void 0?{enabled:g}:{}}),"Couldn't update log-match expression",t.json);if(!t.json)x(`Log-match expression "${n.expression.name}" updated.`);W(Hb,oa(n.expression),{json:t.json})},e7A=async(A,t)=>{let{client:g}=ea(t),i=l(await g.logMatchExpressions.disable(A),"Couldn't disable log-match expression",t.json);if(!t.json)x(`Log-match expression "${i.expression.name}" disabled.`);W(Hb,oa(i.expression),{json:t.json})},$rA=nA("log-match-expressions","Manage CEL log-match expressions").withSubcommands({list:L("list","List log-match expressions",async(A)=>{let{values:t}=F(A,ia);await g7A({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions(na).withExamples(["sazabi log-match-expressions list --json # List log-match expressions"]).build(),get:L("get","Get one log-match expression by ID",async(A)=>{let{values:t,positionals:g}=F(A,ia,{allowPositionals:!0}),i=av(g,t.json);if(!i)return;await n7A(i,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<expression-id>").withOptions(na).withExamples(["sazabi log-match-expressions get <expression-id> --json # Get one expression"]).build(),create:L("create","Create a log-match expression",async(A)=>{let{values:t,positionals:g}=F(A,{...ia,expression:{type:"string"},enabled:{type:"boolean"},disabled:{type:"boolean"}},{allowPositionals:!0}),i=t7A(g,t.json);if(!i)return;let n=(o)=>{if(t.json){u(o);return}D(o)};await i7A(i,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],expression:t.expression,enabled:t.enabled,disabled:t.disabled})}).withPositionalArgs("<name>").withOptions({...na,expression:{type:"string",description:"CEL expression evaluated against ingested logs"},enabled:{type:"boolean",description:"Create the expression enabled"},disabled:{type:"boolean",description:"Create the expression disabled"}}).withExamples([`sazabi log-match-expressions create plain-tickets --expression 'service == "plain"' --json # Create an expression`]).build(),update:L("update","Update a log-match expression",async(A)=>{let{values:t,positionals:g}=F(A,{...ia,name:{type:"string"},expression:{type:"string"},enable:{type:"boolean"},disable:{type:"boolean"}},{allowPositionals:!0}),i=av(g,t.json);if(!i)return;let n=(o)=>{if(t.json){u(o);return}D(o)};await o7A(i,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],name:t.name,expression:t.expression,enable:t.enable,disable:t.disable})}).withPositionalArgs("<expression-id>").withOptions({...na,name:{type:"string",description:"New expression name"},expression:{type:"string",description:"New CEL expression body"},enable:{type:"boolean",description:"Enable the expression"},disable:{type:"boolean",description:"Disable the expression"}}).withExamples([`sazabi log-match-expressions update <expression-id> --expression 'severity == "ERROR"' --json # Update expression CEL`]).build(),disable:L("disable","Disable a log-match expression",async(A)=>{let{values:t,positionals:g}=F(A,ia,{allowPositionals:!0}),i=av(g,t.json);if(!i)return;await e7A(i,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<expression-id>").withOptions(na).withExamples(["sazabi log-match-expressions disable <expression-id> --json # Disable an expression"]).build()}).build();iA();uA();CA();iA();uA();CA();var TrA={id:{label:"ID",type:{kind:"string"}},displayName:{label:"Name",type:{kind:"nullable-string"}},logSourceId:{label:"Log source",type:{kind:"string"}},status:{label:"Status",type:{kind:"string"}},enabled:{label:"Enabled",type:{kind:"boolean"}},errorMessage:{label:"Error",type:{kind:"nullable-string"}},createdAt:{label:"Created",type:{kind:"date"}}},Ev={schema:TrA,columns:["id","displayName","status","enabled","errorMessage","createdAt"],header:"Log streams",emptyMessage:"No log streams found for this log source."},Q7A={layout:"field-list",schema:TrA,fields:["id","logSourceId","displayName","status","enabled","errorMessage","createdAt"],title:"Log stream"},Xb=(A)=>{for(let t of A){let g={};if(t.kind==="url"&&t.url)g[t.label??"Endpoint"]=t.url;else if(t.kind==="hostPort"&&t.host){if(g[t.label??"Host"]=t.port!==void 0?`${t.host}:${t.port}`:t.host,t.extraCredential)g[t.extraCredential.label]=t.extraCredential.value}if(Object.keys(g).length>0){if(zA(g),t.description)IA(t.description)}}},Vg=(A)=>{let t=A.json,g=R({tokenFlag:A.token,jsonMode:t});return{client:f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:t}),json:t,projectId:g.projectId}},Kb=(A,t)=>{let g=A[0];if(!g){if(t)u("Log stream ID is required.");else D("Log stream ID is required. Run 'sazabi log-streams list --log-source-id <id>' to see log stream IDs.");return null}return g},I7A=async(A)=>{let{values:t}=F(A,{...m,"log-source-id":{type:"string"}});if(!t["log-source-id"]){if(t.json)return u("--log-source-id is required.");return D("--log-source-id is required. Run 'sazabi log-sources list' to see log source IDs.")}let{client:g,json:i}=Vg(t),{streams:n}=l(await g.logStreams.list(t["log-source-id"]),"Couldn't list log streams (run 'sazabi log-sources list' to see log source IDs)",i);s(Ev,n,{json:i})},h7A=async(A)=>{let{values:t}=F(A,{...m,"log-source-id":{type:"string"},config:{type:"string"}});if(!t["log-source-id"]){if(t.json)return u("--log-source-id is required.");return D("--log-source-id is required.")}let g={};if(t.config)try{g=JSON.parse(t.config)}catch{if(t.json)return u("--config must be valid JSON.");return D("--config must be valid JSON.")}let{client:i,json:n}=Vg(t),o=l(await i.logStreams.create({logSourceId:t["log-source-id"],config:g}),"Failed to create log stream",n);if(n){X(o);return}x("Log stream created. Provisioning started."),zA({"Log stream ID":o.streamId})},B7A=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=Kb(g,t.json);if(!i)return;let{client:n,json:o}=Vg(t),{stream:e}=l(await n.logStreams.get(i),"Couldn't get log stream (run 'sazabi log-streams list --log-source-id <id>' to see log stream IDs)",o);if(o){X({stream:e});return}if(W(Q7A,e,{json:o}),e.endpointCards&&e.endpointCards.length>0)IA("Point your sender at:"),Xb(e.endpointCards)},GrA=async(A,t)=>{let{values:g,positionals:i}=F(A,m,{allowPositionals:!0}),n=Kb(i,g.json);if(!n)return;let{client:o,json:e}=Vg(g),I=l(await o.logStreams.update({streamId:n,enabled:t}),t?"Failed to enable log stream":"Failed to disable log stream",e);if(e){X(I);return}x(t?"Log stream enabled. It resumes ingesting.":"Log stream disabled. It stops ingesting until re-enabled.")},c7A=async(A)=>{let{values:t,positionals:g}=F(A,{...m,"to-log-source-id":{type:"string"}},{allowPositionals:!0}),i=Kb(g,t.json);if(!i)return;let n=t["to-log-source-id"];if(!n){if(t.json)return u("--to-log-source-id is required.");return D("--to-log-source-id is required. Run 'sazabi log-sources list' to see log source IDs.")}let{client:o,json:e}=Vg(t),{stream:I}=l(await o.logStreams.get(i),"Couldn't get log stream (run 'sazabi log-streams list --log-source-id <id>' to see log stream IDs)",e),{logSource:h}=l(await o.logSources.get(I.logSourceId),"Couldn't get the log stream's current log source",e),{logSource:B}=l(await o.logSources.get(n),"Couldn't get the target log source (run 'sazabi log-sources list' to see log source IDs)",e),c=l(await o.logStreams.reassign({streamId:i,targetLogSourceId:n}),"Failed to reassign log stream",e);if(e){X(c);return}if(x("Log stream reassigned."),zA({"Log stream ID":c.stream.id,From:`${h.name} (${h.provider})`,To:`${B.name} (${B.provider})`}),h.provider!==B.provider)IA(`The log stream keeps its intake key, but future data is now processed as ${B.provider} format — make sure the sender emits that format. Already-ingested data is unaffected.`)},C7A=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=Kb(g,t.json);if(!i)return;let{client:n,json:o}=Vg(t),e=l(await n.logStreams.delete(i),"Failed to delete log stream",o);if(o){X(e);return}x("Log stream deleted.")},JrA=nA("log-streams","Manage log streams").withSubcommands({list:L("list","List log streams for a log source",I7A).withOptions({...z,"log-source-id":{type:"string",description:"Log source ID (required)"}}).withExamples(["sazabi log-streams list --log-source-id <id> # List log streams"]).build(),get:L("get","Get one log stream (check provisioning status)",B7A).withPositionalArgs("<stream-id>").withOptions(z).withExamples(["sazabi log-streams get <id> # Check log stream status"]).build(),create:L("create","Create a log stream under a managed log source",h7A).withOptions({...z,"log-source-id":{type:"string",description:"Log source ID (required)"},config:{type:"string",description:"JSON stream config"}}).withExamples([`sazabi log-streams create --log-source-id <id> --config '{"foo":"bar"}' # Create log stream`]).build(),enable:L("enable","Resume ingestion for a log stream",(A)=>GrA(A,!0)).withPositionalArgs("<stream-id>").withOptions(z).withExamples(["sazabi log-streams enable <id> # Resume ingestion"]).build(),disable:L("disable","Pause ingestion for a log stream",(A)=>GrA(A,!1)).withPositionalArgs("<stream-id>").withOptions(z).withExamples(["sazabi log-streams disable <id> # Pause ingestion"]).build(),reassign:L("reassign","Move a log stream to a different connectionless log source",c7A).withPositionalArgs("<stream-id>").withOptions({...z,"to-log-source-id":{type:"string",description:"Target log source ID (required)"}}).withExamples(["sazabi log-streams reassign <id> --to-log-source-id <id> # Move a log stream"]).build(),delete:L("delete","Delete a log stream",C7A).withPositionalArgs("<stream-id>").withOptions(z).withExamples(["sazabi log-streams delete <id> # Delete a log stream"]).build()}).withExamples(["sazabi log-streams list --log-source-id <id> # List log streams","sazabi log-streams get <id> # Log stream detail and endpoint","sazabi log-streams reassign <id> --to-log-source-id <id> # Move a log stream","sazabi log-streams delete <id> # Delete a log stream"]).build();var r7A={id:{label:"ID",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},modes:{label:"Modes",type:{kind:"string"}}},a7A={schema:r7A,columns:["id","name","modes"],header:"Log source providers",emptyMessage:"No log source providers found."},vrA={id:{label:"ID",type:{kind:"string"}},provider:{label:"Provider",type:{kind:"string"}},mode:{label:"Mode",type:{kind:"string"}},name:{label:"Name",type:{kind:"nullable-string"}},streamCount:{label:"Streams",type:{kind:"number"}},url:{label:"URL",type:{kind:"nullable-string"}},createdAt:{label:"Created",type:{kind:"date"}}},E7A={schema:vrA,columns:["id","provider","mode","name","streamCount","createdAt"],header:"Log sources",emptyMessage:"No log sources found."},y7A={layout:"field-list",schema:vrA,fields:["id","provider","mode","name","streamCount","url","createdAt"],title:"Log source"},w7A=(A,t)=>({...A,url:t?JCA(t,A.provider):void 0}),yv=(A,t)=>{let g=A[0];if(!g){if(t)u("Log source ID is required.");else D("Log source ID is required. Run 'sazabi log-sources list' to see log source IDs.");return null}return g},D7A=async(A)=>{let{values:t}=F(A,m),{client:g,json:i}=Vg(t),{providers:n}=l(await g.logSources.listProviders(),"Couldn't list log source providers (try again)",i),o=[...n].sort((e,I)=>e.name.localeCompare(I.name)).map((e)=>({id:e.id,name:e.name,modes:e.modes.join(", ")}));s(a7A,o,{json:i})},u7A=async(A)=>{let{values:t}=F(A,{...m,provider:{type:"string"},"project-id":{type:"string"}}),{client:g,json:i}=Vg(t),{logSources:n}=l(await g.logSources.list({projectId:t["project-id"],provider:t.provider}),"Couldn't list log sources (check the active project and try again)",i);s(E7A,n,{json:i})},b7A=async(A)=>{let{values:t,positionals:g}=F(A,{...m,metadata:{type:"string"},mode:{type:"string"},"project-id":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Log source provider is required.");return D("Log source provider is required. Use 'sazabi log-sources providers' to see available providers.")}if(t.mode&&t.mode!=="managed"&&t.mode!=="connectionless"){if(t.json)return u("--mode must be 'managed' or 'connectionless'.");return D("--mode must be 'managed' or 'connectionless'.")}let n;if(t.metadata)try{n=JSON.parse(t.metadata)}catch{if(t.json)return u("--metadata must be valid JSON.");return D("--metadata must be valid JSON.")}let{client:o,json:e}=Vg(t),I=l(await o.logSources.create({provider:i,metadata:n,mode:t.mode,projectId:t["project-id"]}),"Failed to create log source",e);if(e){X(I);return}if(x("Log source created."),zA({"Log source ID":I.logSource.id,...I.logSource.name?{Name:I.logSource.name}:{},Provider:I.logSource.provider,Mode:I.logSource.mode,...I.streamId?{"Log stream ID":I.streamId}:{},...I.publicKey?{"Public key":I.publicKey}:{}}),I.endpointCards&&I.endpointCards.length>0)IA("Point your sender at:"),Xb(I.endpointCards);if(I.publicKey)jg("Store the public key securely — it is only shown once.")},l7A=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=yv(g,t.json);if(!i)return;let{client:n,json:o,projectId:e}=Vg(t),{logSource:I}=l(await n.logSources.get(i),"Couldn't get log source (run 'sazabi log-sources list' to see log source IDs)",o);if(o){X({logSource:I});return}if(W(y7A,w7A({id:I.id,provider:I.provider,mode:I.mode,name:I.name,streamCount:I.streamCount,createdAt:I.createdAt},e),{json:o}),I.streams.length>0){s(Ev,I.streams,{json:o});for(let h of I.streams)if(h.endpointCards&&h.endpointCards.length>0)IA(`Endpoint for log stream "${h.displayName??h.id}":`),Xb(h.endpointCards)}},PrA=async(A,t)=>{let{values:g,positionals:i}=F(A,m,{allowPositionals:!0}),n=yv(i,g.json);if(!n)return;let{client:o,json:e}=Vg(g),I=l(await o.logSources.update({logSourceId:n,enabled:t}),t?"Failed to enable log source":"Failed to disable log source",e);if(e){X(I);return}x(t?"Log source enabled. Its log streams resume ingesting.":"Log source disabled. Its log streams stop ingesting until re-enabled.")},N7A=async(A)=>{let{values:t,positionals:g}=F(A,m,{allowPositionals:!0}),i=yv(g,t.json);if(!i)return;let{client:n,json:o}=Vg(t),e=l(await n.logSources.delete(i),"Failed to delete log source",o);if(o){X(e);return}if(e.teardownError){jg(`Log source deleted, but remote cleanup failed (remove the remote resources manually): ${e.teardownError}`);return}x("Log source deleted.")},U7A=async(A)=>{let{values:t}=F(A,{...m,provider:{type:"string"}});if(!t.provider){if(t.json)return u("--provider is required.");return D("--provider is required. Use 'sazabi log-sources providers' to see providers with skills.")}let{client:g,json:i}=Vg(t),{providers:n}=l(await g.logSources.listProviders(),"Couldn't list log source providers (try again)",i),o=n.find((e)=>e.id===t.provider);if(!o){let e=`Unknown log source provider: '${t.provider}'. Use 'sazabi log-sources providers' to see available providers.`;if(i)return u(e);return D(e)}if(!o.setupSkill){if(i)return u(`No setup skill available for ${t.provider}.`);return D(`No setup skill available for ${t.provider}. This log source provider does not have an agent-ready skill yet.`)}if(i){X({provider:t.provider,setupSkill:o.setupSkill});return}IA(o.setupSkill)},RrA=L("list","List log sources",u7A).withOptions({...z,provider:{type:"string",description:"Filter by log source provider"},"project-id":{type:"string",description:"Project ID"}}).withExamples(["sazabi log-sources list # List all log sources","sazabi log-sources list --provider vercel # Filter by provider"]).build(),frA=L("delete","Delete a log source",N7A).withPositionalArgs("<log-source-id>").withOptions(z).withExamples(["sazabi log-sources delete <id> # Delete a log source and deactivate its keys"]).build(),OrA=nA("log-sources","Manage log sources").withSubcommands({providers:L("providers","List supported log source providers",D7A).withOptions(z).withExamples(["sazabi log-sources providers # List all providers","sazabi log-sources providers --json # Output as JSON"]).build(),list:RrA,ls:RrA,create:L("create","Create a log source",b7A).withPositionalArgs("<provider>").withOptions({...z,metadata:{type:"string",description:"JSON credentials for managed setup"},mode:{type:"string",description:"Setup mode: managed or connectionless (inferred from --metadata when omitted)"},"project-id":{type:"string",description:"Project ID"}}).withExamples(["sazabi log-sources create otel # Connectionless: mints a keyed endpoint",`sazabi log-sources create fly_io --metadata '{"apiToken":"..."}' # Managed: connects with credentials`]).build(),get:L("get","Get one log source",l7A).withPositionalArgs("<log-source-id>").withOptions(z).withExamples(["sazabi log-sources get <id> # Log source details, log streams, and endpoints"]).build(),enable:L("enable","Resume ingestion for a log source's log streams",(A)=>PrA(A,!0)).withPositionalArgs("<log-source-id>").withOptions(z).withExamples(["sazabi log-sources enable <id> # Resume ingestion"]).build(),disable:L("disable","Pause ingestion for a log source's log streams",(A)=>PrA(A,!1)).withPositionalArgs("<log-source-id>").withOptions(z).withExamples(["sazabi log-sources disable <id> # Pause ingestion"]).build(),delete:frA,remove:frA,skill:L("skill","Show setup skill for a log source provider",U7A).withOptions({...z,provider:{type:"string",description:"Log source provider (required)"}}).withExamples(["sazabi log-sources skill --provider gcp # Show GCP setup skill","sazabi log-sources skill --provider fly_io # Show Fly.io setup skill"]).build()}).withExamples(["sazabi log-sources providers # List available providers","sazabi log-sources list # List log sources","sazabi log-sources create otel # Connectionless: mints a keyed endpoint",`sazabi log-sources create fly_io --metadata '{"apiToken":"..."}' # Managed: connects with credentials`,"sazabi log-sources skill --provider gcp # Show agent setup skill"]).build();iA();iA();$Q();pr();uA();import*as Mi from"node:fs";import*as _b from"node:readline";var Qa=(A)=>new Promise((t)=>setTimeout(t,A));var L7A=(A)=>{return`${A.getTime()*1e6}`},S7A=(A)=>Object.entries(A).map(([t,g])=>({key:t,value:{stringValue:g}})),F7A=[{pattern:/\b(?:fatal|critical|crit)\b/i,severityNumber:21,severityText:"FATAL"},{pattern:/\b(?:error|err)\b/i,severityNumber:17,severityText:"ERROR"},{pattern:/\b(?:warn|warning)\b/i,severityNumber:13,severityText:"WARN"},{pattern:/\bdebug\b/i,severityNumber:5,severityText:"DEBUG"},{pattern:/\btrace\b/i,severityNumber:1,severityText:"TRACE"}],M7A={severityNumber:9,severityText:"INFO"},k7A=(A)=>{let t=null;for(let{pattern:g,severityNumber:i,severityText:n}of F7A){let o=g.exec(A);if(o&&(t===null||o.index<t.index))t={index:o.index,severityNumber:i,severityText:n}}return t?{severityNumber:t.severityNumber,severityText:t.severityText}:M7A},zrA=(A,t,g={})=>{let n=L7A(new Date),o=g.serviceName??"sazabi-cli",e=S7A(g.attributes??{}),I=A.filter((h)=>h.trim().length>0).map((h)=>({timeUnixNano:n,observedTimeUnixNano:n,...k7A(h),body:{stringValue:h},attributes:e}));return{resourceLogs:[{resource:{attributes:[{key:"service.name",value:{stringValue:o}},{key:"sazabi.public_key",value:{stringValue:t}}]},scopeLogs:[{scope:{name:"sazabi-cli-forward",version:"1.0.0"},logRecords:I}]}]}};function Y7A(A,t,g){return A===1?t:g??`${t}s`}function In(A,t,g){return`${A} ${Y7A(A,t,g)}`}CA();Yn();var $7A="15003",G7A="SAZABI_INTERNAL_LOG_FORWARDING_SECRET",T7A="SAZABI_INTERNAL_LOG_FORWARDING_SOURCE",J7A="sazabi.source",P7A="sazabi.internal.source",R7A=(A)=>{return A.startsWith("[")&&A.endsWith("]")?A.slice(1,-1):A},f7A=(A)=>{let t=R7A(A);return t==="localhost"||t==="127.0.0.1"||t==="::1"},v7A=(A)=>{let t=(()=>{try{return new URL(A)}catch{return null}})();if(!t)return;if(!f7A(t.hostname))return;return t.protocol="http:",t.port=$7A,t.pathname="",t.search="",t.hash="",t.toString()},O7A=async(A,t)=>{if(!t)IA("Ensuring public key exists...");let g=await A.publicKeys.ensureLogForwarding({});if(!g.success){if(!t)Gn(`Failed to ensure public key: ${g.error}. Pass --public-key <value> or check your project access and try again.`);return null}if(!t)x(`Using public key: ${g.value.publicKey.name}`);return{value:g.value.publicKey.value,projectId:g.value.publicKey.projectId,createdAt:g.value.publicKey.createdAt}},z7A=({explicitPublicKey:A,cachedPublicKey:t,cachedPublicKeyProjectId:g,activeProjectId:i})=>{let n=A?.trim();if(n)return n;let o=t?.trim();if(!o)return;return g?.trim()===i?o:void 0},m7A=(A)=>{if(!A||A.length===0)return{success:!0,value:{}};let t={};for(let g of A){let i=g.indexOf("=");if(i<=0)return{success:!1,error:`Invalid attribute "${g}". Use key=value.`};let n=g.slice(0,i).trim();if(!n)return{success:!1,error:`Invalid attribute "${g}". Attribute key is required.`};t[n]=g.slice(i+1)}return{success:!0,value:t}},W7A=(A)=>{let t=process.env[G7A]?.trim();if(!t)return;let g=process.env[T7A]?.trim()||A[P7A]?.trim()||A[J7A]?.trim()||void 0;return{secret:t,...g?{source:g}:{}}},wv=(A,t,g,i,n,o,e,I,h,B,c)=>{return async()=>{if(A.length===0)return;let C=zrA(A,i,I),r=H7A(C);if(A.length=0,r===0)return;if(!B)IA(`Forwarding ${In(r,"log")}...`);let a=await g.logs.forward({publicKey:i,logs:C,region:o,...e?{projectId:e}:{},...h?{sazabiInternalForwarding:h}:{}});while(!a.success&&s7A(a)&&x7A(n)){if(!B)IA("Public key is still propagating to intake (usually under a minute); retrying...");await Qa(_7A),a=await g.logs.forward({publicKey:i,logs:C,region:o,...e?{projectId:e}:{},...h?{sazabiInternalForwarding:h}:{}})}if(!a.success){if(X7A(a)){l(a,"Failed to forward logs",B);return}if(t.totalFailed+=r,!B)jg(`Failed to forward logs: ${a.error}`);c?.({forwarded:0,failed:r});return}t.totalForwarded+=a.value.forwardedCount,t.totalFailed+=a.value.failedCount,c?.({forwarded:a.value.forwardedCount,failed:a.value.failedCount})}},Z7A=async(A,t,g,i,n,o,e,I,h,B,c)=>{let C=Mi.createReadStream(A),r=_b.createInterface({input:C,crlfDelay:Number.POSITIVE_INFINITY}),a=[],y={totalForwarded:0,totalFailed:0},w=wv(a,y,t,g,i,n,o,e,I,B,(b)=>c?.push(b));try{for await(let b of r)if(a.push(b),a.length>=h)await w()}catch(b){Gn(`Couldn't read ${A} (check that the file exists and is readable): ${b instanceof Error?b.message:String(b)}`);return}if(await w(),B);else if(MA(),Gi(jA.muted("─".repeat(80))),x(`Forwarded ${In(y.totalForwarded,"log")}.`),y.totalFailed>0)jg(`Failed to forward ${In(y.totalFailed,"log")}.`)},V7A=async(A,t,g,i,n,o,e,I,h,B)=>{let c=_b.createInterface({input:process.stdin,output:process.stdout,terminal:!1}),C=[],r={totalForwarded:0,totalFailed:0},a=wv(C,r,A,t,g,i,n,o,e,h,(y)=>B?.push(y));try{for await(let y of c)if(C.push(y),C.length>=I)await a()}catch(y){Gn(`Couldn't read from stdin (check the input stream and try again): ${y instanceof Error?y.message:String(y)}`);return}if(await a(),h);else if(MA(),Gi(jA.muted("─".repeat(80))),x(`Forwarded ${In(r.totalForwarded,"log")}.`),r.totalFailed>0)jg(`Failed to forward ${In(r.totalFailed,"log")}.`)},j7A=async(A,t,g,i,n,o,e,I,h,B,c)=>{let C=[],r={totalForwarded:0,totalFailed:0},a=wv(C,r,t,g,i,n,o,e,I,B,(oA)=>c?.push(oA)),y=null,w=null,b=async()=>{if(w)clearTimeout(w);if(y)y.close();if(await a(),B);else if(MA(),Gi(jA.muted("─".repeat(80))),x(`Forwarded ${In(r.totalForwarded,"log")}.`),r.totalFailed>0)jg(`Failed to forward ${In(r.totalFailed,"log")}.`)};process.on("SIGINT",async()=>{MA(),IA("Interrupted, flushing remaining logs..."),await b(),process.exit(0)});let N=null,k=null,T=!1,V=0,P=async()=>{if(T)return;T=!0;try{if((await Mi.promises.stat(A)).size<V)V=0;N=Mi.createReadStream(A,{encoding:"utf8",start:V}),k=_b.createInterface({input:N,crlfDelay:Number.POSITIVE_INFINITY});for await(let bA of k)if(C.push(bA),C.length>=h)await a();V=(await Mi.promises.stat(A)).size}catch(oA){Gn(`Couldn't read ${A} (check that the file exists and is readable): ${oA instanceof Error?oA.message:String(oA)}`)}finally{T=!1}};await P(),y=Mi.watch(A,async(oA)=>{if(oA==="change"){if(w)clearTimeout(w);w=setTimeout(async()=>{if(T)return;if(N)N.close();if(k)k.close();await Qa(50),await P()},100)}})},mrA=async(A)=>{let t=A.batchSize??100;if(t<=0){if(A.json)return u("Batch size must be a positive number.");throw D("Batch size must be a positive number."),Error("Unreachable")}let g=l(m7A(A.attributes),"Invalid --attribute value",A.json===!0);if(A.follow&&!A.file){if(A.json)return u("--follow requires --file to be specified.");throw D("--follow requires --file to be specified."),Error("Unreachable")}let i=(()=>{let T=yt();if(!T.success)throw D(`Couldn't read settings (check that ~/.sazabi/settings.json is readable): ${T.error}`),Error("Unreachable");return T.value})(),n=l(on(i),"Couldn't resolve profile (run 'sazabi profiles list' to see available profiles)"),o=A.json===!0,e=R({tokenFlag:A.token,jsonMode:o}),I=Fi({cliFlag:A.apiBaseUrl,globalUrl:n.apiBaseUrl,globalDomain:n.apiDomain,buildUrlFromDomain:(T)=>`https://api.${T}`,defaultUrl:"https://api.sazabi.com"});if(!o)JA("Forwarding logs");let h=await fb({token:e.token,projectId:e.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:o});if(!o)IA(`Project: ${h.name}`);let B;if(A.region)B=q7A(A.region,o);else B=h.region;if(!o)IA(`Region: ${B}`);if(!o)IA(`Batch size: ${t}`);let c={serviceName:A.service?.trim()||void 0,attributes:g},C=W7A(g),r=A.intakeBaseUrl??n.intakeBaseUrl??v7A(I)??(n.intakeDomain?fCA(n.intakeDomain,B):void 0)??`https://otlp.${B}.intake.sazabi.com`;try{let T=new URL(r);if(!o&&/\.intake\.sazabi\.(dev|com)$/.test(T.host)&&!T.host.startsWith("otlp."))jg("Intake base URL may not be the OTLP endpoint. For Sazabi, prefer https://otlp.{region}.intake.sazabi.dev or .com as appropriate.")}catch{}let a=qi({token:e.token,projectId:e.projectId,baseUrl:I,intakeBaseUrl:r}),y=z7A({explicitPublicKey:A.publicKey,cachedPublicKey:n.forwardPublicKey,cachedPublicKeyProjectId:n.forwardPublicKeyProjectId,activeProjectId:h.id}),w;if(!y){let T=await O7A(a,o);if(!T)throw D("Failed to ensure public key. Pass --public-key <value> or check your project access and try again."),Error("Unreachable");y=T.value;let V=Date.parse(T.createdAt);w=Number.isFinite(V)?V:void 0;let P=en(i,{forwardPublicKey:y,forwardPublicKeyProjectId:T.projectId});if(P.success){let oA=Ht(P.value);if(!oA.success)jg(`Failed to store public key: ${oA.error}`)}}if(!o)MA(),Gi(jA.muted("─".repeat(80))),MA();let b=!A.follow,N=[],k={forwarded:0,failed:0};if(A.follow&&A.file)await j7A(A.file,a,y,w,B,e.projectId,c,C,t,o,b?N:void 0);else if(A.file)await Z7A(A.file,a,y,w,B,e.projectId,c,C,t,o,N);else await V7A(a,y,w,B,e.projectId,c,C,t,o,N);for(let T of N)k.forwarded+=T.forwarded,k.failed+=T.failed;if(o){let T={forwardedCount:k.forwarded,failedCount:k.failed,batches:N,project:{id:h.id,name:h.name,region:B},intakeBaseUrl:r,batchSize:t,follow:Boolean(A.follow),file:A.file??void 0};console.log(JSON.stringify(T))}},H7A=(A)=>{return A.resourceLogs?.reduce((t,g)=>t+(g.scopeLogs?.reduce((i,n)=>i+(n.logRecords?.length??0),0)??0),0)??0},X7A=(A)=>{if(A.success)return!1;if(A.errorPayload)return!0;if(A.statusCode!==void 0&&A.statusCode<500)return!0;return A.error.startsWith("Authentication failed")||A.error.startsWith("Client error (")},K7A=120000,_7A=5000,s7A=(A)=>!A.success&&(A.statusCode===401||A.statusCode===403||A.error.startsWith("Authentication failed")),x7A=(A,t=Date.now())=>A!==void 0&&Number.isFinite(A)&&t-A<K7A,q7A=(A,t)=>{let g=uB.safeParse(A);if(g.success)return g.data;let i=`Invalid region: ${A}. Valid regions: ${uB.options.join(", ")}.`;if(t)return u(i);return D(i)};iA();uA();CA();import{readFile as d7A}from"node:fs/promises";var p7A={result:{label:"Result",type:{kind:"string"}},format:{label:"Format",type:{kind:"string"}},meta:{label:"Meta",type:{kind:"custom",render:(A)=>JSON.stringify(A),serialize:(A)=>A}}},AqA={layout:"field-list",schema:p7A,fields:["result","format","meta"]},WrA=async(A)=>{if(!A.query&&!A.file){if(A.json)return u("Pass --query or --file.");return D("Pass --query or --file.")}if(A.query&&A.file){if(A.json)return u("Pass either --query or --file, not both.");return D("Pass either --query or --file, not both.")}let t;if(A.query!==void 0)t=A.query;else try{t=await d7A(A.file,"utf8")}catch(o){let e=`Couldn't read query file (check that the path exists and is readable): ${o instanceof Error?o.message:String(o)}`;if(A.json)return u(e);return D(e)}if(t.trim().length===0){if(A.json)return u("Query cannot be empty.");return D("Query cannot be empty.")}let g=R({tokenFlag:A.token,projectIdFlag:A.project,jsonMode:A.json}),i=f({token:g.token,projectId:g.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:A.json}),n=l(await i.logs.nativeQuery({query:t}),"Couldn't run native log query (check the query syntax and try again)",A.json);if(A.json){W(AqA,n,{json:!0});return}IA(`Backend ${n.meta.backendId} returned ${n.result.length} characters in ${n.meta.took}ms${n.meta.truncated?" (truncated)":""}`),process.stdout.write(n.result.endsWith(`
8753
8753
  `)?n.result:`${n.result}
8754
8754
  `)};iA();uA();CA();iA();var tqA=/^(\d+)(s|m|h|d)$/u,gqA=(A,t)=>{let g=tqA.exec(A.trim());if(!g){if(t)return u("Duration must use s, m, h, or d units, for example 30m.");return D("Duration must use s, m, h, or d units, for example 30m.")}let i=Number(g[1]),n=g[2];return i*(n==="s"?1000:n==="m"?60000:n==="h"?3600000:86400000)},ZrA=(A,t,g)=>{let i=new Date(A);if(Number.isNaN(i.getTime())){let n=`${t} must be a valid ISO-8601 timestamp.`;if(g)return u(n);return D(n)}return i.toISOString()},JB=(A)=>{if(A.last&&(A.from||A.to)){if(A.json)return u("Use either --last or --from/--to, not both.");return D("Use either --last or --from/--to, not both.")}if(A.last){let i=new Date,n=new Date(i.getTime()-gqA(A.last,A.json));if(!Number.isFinite(n.getTime())||!Number.isFinite(i.getTime())){if(A.json)return u("--last is out of the supported date range.");return D("--last is out of the supported date range.")}return{startDate:n.toISOString(),endDate:i.toISOString()}}let t=A.from?ZrA(A.from,"--from",A.json):void 0,g=A.to?ZrA(A.to,"--to",A.json):void 0;if(t&&g&&new Date(t)>=new Date(g)){if(A.json)return u("--from must be before --to.");return D("--from must be before --to.")}return{startDate:t,endDate:g}};var nqA={patterns:{label:"Patterns",type:{kind:"custom",render:(A)=>`${Array.isArray(A)?A.length:0} patterns`,serialize:(A)=>A}},meta:{label:"Meta",type:{kind:"custom",render:(A)=>JSON.stringify(A),serialize:(A)=>A}}},iqA={layout:"field-list",schema:nqA,fields:["patterns","meta"]},oqA={serviceName:{label:"Service",type:{kind:"nullable-string",emptyLabel:"(unknown)"}},severity:{label:"Severity",type:{kind:"custom",render:(A)=>typeof A==="string"&&A.length>0?Yi(A):"(none)",serialize:(A)=>A}},occurrences:{label:"Occurrences",type:{kind:"number"},align:"right"},lastSeen:{label:"Last Seen",type:{kind:"nullable-date",emptyLabel:"(never)"}},pattern:{label:"Pattern",type:{kind:"truncated",maxLength:140}},representativeId:{label:"Representative",type:{kind:"nullable-string",emptyLabel:"(none)"}}},eqA={schema:oqA,columns:["serviceName","severity","occurrences","lastSeen","pattern","representativeId"],header:{title:"Log patterns",variant:"search"},emptyMessage:"No matching log patterns."},QqA=(A)=>{let t=JB(A);return{...A.query?{query:A.query}:{},...A.severity?{severity:A.severity}:{},...t.startDate?{startDate:t.startDate}:{},...t.endDate?{endDate:t.endDate}:{},limit:A.limit??25}},VrA=async(A)=>{let t=R({tokenFlag:A.token,projectIdFlag:A.project,jsonMode:A.json}),g=f({token:t.token,projectId:t.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:A.json}),i=l(await g.logs.patterns(QqA(A)),"Failed to query log patterns",A.json);if(A.json){W(iqA,i,{json:!0});return}IqA(i)},IqA=(A)=>{if(A.patterns.length>0)IA(`Returned ${A.meta.count} pattern${A.meta.count===1?"":"s"} in ${A.meta.took}ms`);s(eqA,A.patterns,{count:A.meta.count})};iA();uA();CA();CA();var sb=(A)=>{let t={};for(let g of A??[]){let i=g.indexOf("=");if(i<=0)return St(`Invalid attribute filter "${g}". Use key=value.`);let n=g.slice(0,i).trim();if(!n)return St(`Invalid attribute filter "${g}". Attribute key is required.`);t[n]=g.slice(i+1)}return Zt(t)};var xb=500,jrA=new Set(["eq","neq","in","contains","starts_with","gt","gte","lt","lte","between","exists"]),hqA=(A)=>{if(A==="@timestamp")return"timestamp";return A},qb=(A,t)=>{for(let g of t){let i=A[g];if(i===void 0||i===null)continue;if(typeof i==="string")return i;if(typeof i==="number"||typeof i==="boolean")return String(i)}return""},BqA=(A)=>{let t=qb(A,["@timestamp","timestamp","time","ts","date"]);if(!t)return eg("(no time)");return eo(t)},cqA=(A)=>{return qb(A,["body","message","log","text","content","msg"])||eg("(no message)")},CqA=(A)=>{return qb(A,["severity","level","log_level","priority"])},rqA=(A)=>{return qb(A,["service","service_name","serviceName","source"])},aqA=(A,t)=>{let g={};if(!t.omitSearch)g.search={query:A,mode:t.mode??"all",...t.searchFields?.length?{fields:t.searchFields}:{}};if(t.cursor!==void 0||t.limit!==void 0||t.all)g.pagination={limit:t.limit??(t.all?100:50),...t.cursor!==void 0?{cursor:t.cursor}:{}};if(t["sort-field"])g.sort={field:hqA(t["sort-field"]),direction:t["sort-direction"]??"desc"};if(t.select){let n=t.select.split(",").map((o)=>o.trim()).filter((o)=>o.length>0);if(n.length>0)g.select=n}let i=DqA(t);if(!i.ok)return{ok:!1,errors:i.errors};if(i.filters.length>0)g.filters=i.filters;return{ok:!0,input:g}};var EqA=(A)=>{if(A==="true")return!0;if(A==="false")return!1;let t=Number(A);if(A.trim()!==""&&Number.isFinite(t))return t;return A},yqA=(A)=>{let t=Number(A);if(A.trim()!==""&&Number.isFinite(t))return t;return A},wqA=(A)=>{let t=A.indexOf("=");if(t<=0)return{ok:!1,error:"Filter must use <field>.<op>=<value>."};let g=A.slice(0,t),i=A.slice(t+1),n=g.lastIndexOf(".");if(n<=0||n===g.length-1)return{ok:!1,error:"Filter must use <field>.<op>=<value>."};let o=g.slice(0,n),e=g.slice(n+1);if(!jrA.has(e))return{ok:!1,error:`Unsupported filter operator: ${e}. Valid operators: ${[...jrA].join(", ")}.`};if(e==="in"){let I=i.split(",").map((h)=>yqA(h.trim())).filter((h)=>h!=="");if(I.length===0)return{ok:!1,error:"in filters must include at least one value."};return{ok:!0,filter:{field:o,op:e,value:I}}}if(e==="between"){let I=i.includes("..")?i.split(".."):i.split(",");if(I.length!==2)return{ok:!1,error:"between filters must use <from>..<to>."};let[h,B]=I.map((c)=>c.trim());if(!h||!B)return{ok:!1,error:"between filters must use <from>..<to>."};return{ok:!0,filter:{field:o,op:e,value:{from:h,to:B}}}}if(e==="exists"){if(i!=="true"&&i!=="false")return{ok:!1,error:"exists filters must use true or false."};return{ok:!0,filter:{field:o,op:e,value:i==="true"}}}return{ok:!0,filter:{field:o,op:e,value:EqA(i)}}},DqA=(A)=>{let t=[],g=[],i=JB({from:A.from,to:A.to,last:A.last,json:A.json});if(i.startDate&&i.endDate)t.push({field:"timestamp",op:"between",value:{from:i.startDate,to:i.endDate}});else if(i.startDate)t.push({field:"timestamp",op:"gte",value:i.startDate});else if(i.endDate)t.push({field:"timestamp",op:"lte",value:i.endDate});if(A.service)t.push({field:"service",op:"eq",value:A.service});if(A.severity)t.push({field:"severity",op:"eq",value:A.severity});if(A.env)t.push({field:"environment",op:"eq",value:A.env});if(A.traceId)t.push({field:"trace_id",op:"eq",value:A.traceId});let n=sb(A.attributes);if(n.success)for(let[o,e]of Object.entries(n.value))t.push({field:`attributes[${o}]`,op:"eq",value:e});else g.push(n.error);for(let o of A.filters??[]){let e=wqA(o);if(e.ok)t.push(e.filter);else g.push(`${o}: ${e.error}`)}if(g.length>0)return{ok:!1,errors:g};return{ok:!0,filters:t}},HrA=async(A,t)=>{let g=R({tokenFlag:t.token,projectIdFlag:t.project,jsonMode:t.json}),i=f({token:g.token,projectId:g.projectId,apiBaseUrlFlag:t["api-base-url"],jsonMode:t.json}),n=aqA(A,t);if(!n.ok){if(t.json)return u({success:!1,error:"Invalid log query filters",errors:n.errors});return D(`Invalid log query filters: ${n.errors.join("; ")}`)}let o=n.input,e=t.all?await uqA(i,o,t):l(await i.logs.query(o),"Couldn't query logs (adjust the filters or time window and try again)",t.json);if(t.json){X(e);return}bqA(e)},uqA=async(A,t,g)=>{let i=[],n=t.pagination?.cursor,o=0;do{let e={...t,pagination:{limit:t.pagination?.limit??g.limit??100,...n?{cursor:n}:{}}},I=l(await A.logs.query(e),"Failed to query logs",g.json);i.push(...I.data),o+=I.meta.took,n=I.nextCursor}while(n);return{data:i,nextCursor:null,meta:{count:i.length,took:o}}},bqA=(A)=>{let{data:t,nextCursor:g,meta:i}=A;if(t.length===0){ae("No matching log rows. Widen the time window with --last or loosen filters.");return}IA(`Returned ${i.count} row${i.count===1?"":"s"} in ${i.took}ms`);let n=t.map((o)=>{let e=o,I=CqA(e);return{time:BqA(e),severity:I?Yi(I,I):jA.muted(eg("(sev)")),service:rqA(e)||eg("(service)"),message:Mg(cqA(e),200)}});dn(n,[{header:"Time (UTC)",key:"time"},{header:"Severity",key:"severity"},{header:"Service",key:"service"},{header:"Message",key:"message"}],{header:{title:"Log query results",variant:"search",count:i.count}}),$i({type:"cursor",nextCursor:g})};iA();uA();CA();var lqA={backend:{label:"Backend",type:{kind:"custom",render:(A)=>{let t=A;return`${t.name} (${t.id})`},serialize:(A)=>A}},features:{label:"Features",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"(none)",serialize:(A)=>A}},commands:{label:"Commands",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"(none)",serialize:(A)=>A}},question:{label:"Question",type:{kind:"custom",render:(A)=>String(A??""),serialize:(A)=>A}},indexStatus:{label:"Index",type:{kind:"custom",render:(A)=>String(A??"unknown"),serialize:(A)=>A}},selectedAttributeKeys:{label:"Selected Attributes",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"(none)",serialize:(A)=>A}},selectedBundles:{label:"Selected Bundles",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.map((t)=>{let g=t;return`${g.service} (${g.keys.length} keys)`}).join("; "):"(none)",serialize:(A)=>A}},queryableFields:{label:"Queryable",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"(none)",serialize:(A)=>A}},searchableFields:{label:"Searchable",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"(none)",serialize:(A)=>A}},observedServiceNames:{label:"Observed Services",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"(none)",serialize:(A)=>A}},observedAttributeKeys:{label:"Observed Attributes",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"(none)",serialize:(A)=>A}},schemaContext:{label:"Schema Context",type:{kind:"custom",render:(A)=>A?JSON.stringify(A):"(none)",serialize:(A)=>A}}},NqA={layout:"field-list",schema:lqA,fields:["backend","features","commands","question","indexStatus","selectedAttributeKeys","selectedBundles","queryableFields","searchableFields","observedServiceNames","observedAttributeKeys","schemaContext"]},XrA=async(A)=>{let t=R({tokenFlag:A.token,projectIdFlag:A.project,jsonMode:A.json}),g=f({token:t.token,projectId:t.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:A.json}),i=l(await g.logs.schema({...A.question?{question:A.question}:{},...A["top-k"]!==void 0?{topK:A["top-k"]}:{}}),"Couldn't fetch log schema (check the active project and try again)",A.json);if(A.json){W(NqA,i,{json:!0});return}UqA(i)},UqA=(A)=>{if(JA("Log backend"),zA({Backend:`${A.backend.name} (${A.backend.id})`,Kind:A.backend.kind,Commands:A.commands.join(", "),Features:A.features.join(", ")||"(none)",Question:A.question??"(none)",Index:A.indexStatus}),JA("Selected schema"),zA({Attributes:A.selectedAttributeKeys.join(", ")||"(none)",Bundles:String(A.selectedBundles.length)}),A.selectedBundles.length>0)dn(A.selectedBundles.map((t)=>({service:Mg(t.service,40),keys:Mg(t.keys.join(", "),80),rows:String(t.rowCount)})),[{header:"Service",key:"service"},{header:"Keys",key:"keys"},{header:"Rows",key:"rows"}]);if(JA("Normalized fields"),zA({Queryable:A.queryableFields.join(", ")||"(none)",Searchable:A.searchableFields.join(", ")||"(none)"}),A.observedServiceNames.length>0)dn(A.observedServiceNames.map((t)=>({service:Mg(t,80)})),[{header:"Observed Services",key:"service"}])};iA();pr();uA();CA();Yn();var KrA=["ERROR","WARN","INFO","DEBUG","TRACE"],LqA="3010",SqA=(A)=>{return A.startsWith("[")&&A.endsWith("]")?A.slice(1,-1):A},FqA=(A)=>{let t=SqA(A);return t==="localhost"||t==="127.0.0.1"||t==="::1"},MqA=200,kqA=(A,t)=>{if(!t)return"";let g=t.kind==="all"?Object.keys(A).sort():t.keys,i=[];for(let n of g){let o=A[n];if(o===void 0)continue;i.push(jA.muted(`${n}=${Mg(o,MqA)}`))}return i.length>0?` ${i.join(" ")}`:""},YqA=({log:A,attrsDisplay:t})=>{let g=eo(A.timestamp).split("T")[1]??A.timestamp,i=Yi(A.severity,A.severity.padEnd(7)),n=jA.cyan(A.service.padEnd(20)),o=A.body.length>120?`${A.body.substring(0,117)}...`:A.body,e=kqA(A.attributes,t);return`[${g}] ${i} ${n} ${o}${e}`},$qA=(A)=>{if(A===void 0)return;if(A.trim().toLowerCase()==="all")return{kind:"all"};let t=A.split(",").map((g)=>g.trim()).filter((g)=>g.length>0);return t.length>0?{kind:"keys",keys:t}:void 0},srA=async(A)=>{let t=l(pi(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)"),g=A.json??!1,i=JqA(t,A.apiBaseUrl),n=TqA(A.severities,g),o=Dv(A.services),e=Dv(A.environments),I=sb(A.attribute);if(!I.success){if(g)return u(I.error);return D(I.error)}let h=Object.keys(I.value).length>0?I.value:void 0,B=$qA(A.attrs),c=R({tokenFlag:A.token,jsonMode:g}),C=await fqA({apiBaseUrlFlag:A.apiBaseUrl,jsonMode:g,projectId:c.projectId,regionFlag:A.region,token:c.token}),r=qi({token:c.token,projectId:c.projectId,baseUrl:i,tailBaseUrl:RqA(t,A.tailBaseUrl,C,i)}),a={severities:n,services:o,environments:e,searchTerm:A.search,traceId:A.traceId,attributes:h},y=new AbortController,w,b=0,N,k,T=()=>{w="interrupted",y.abort()};if(!g)GqA({attributes:h,environments:e,region:C,search:A.search,services:o,severities:n,traceId:A.traceId});let V=l(await r.logs.tail({...c.projectId?{projectId:c.projectId}:{},...C?{region:C}:{},filters:a,signal:y.signal}),"Couldn't tail logs (check your network connection and try again)",g);if(!g)x("Connected. Waiting for logs..."),IA("Press Ctrl+C to stop (auto-reconnects on disconnect)."),MA();if(process.on("SIGINT",T),A.duration&&A.duration>0)k=setTimeout(()=>{w="duration",y.abort()},A.duration*1000);try{for await(let P of V){if(b+=1,g){X(P);continue}Gi(YqA({log:P,attrsDisplay:B}))}}catch(P){if(w==="interrupted"||w==="duration"||P instanceof Error&&P.name==="AbortError")N=void 0;else N=P instanceof Error?P:Error(String(P))}finally{if(process.removeListener("SIGINT",T),k)clearTimeout(k)}if(N){if(g)return u(N.message);MA(),WB(),Gn(N.message);return}if(g)return;if(MA(),w==="duration")IA("Duration reached, closing connection...");if(w==="interrupted")IA("Interrupted, closing connection...");WB(),IA(`Connection closed. Received ${In(b,"log")}.`)},GqA=(A)=>{if(JA("Tailing logs"),A.severities?.length)IA(`Severities: ${A.severities.join(", ")}`);if(A.services?.length)IA(`Services: ${A.services.join(", ")}`);if(A.environments?.length)IA(`Environments: ${A.environments.join(", ")}`);if(A.search)IA(`Search: ${A.search}`);if(A.traceId)IA(`Trace ID: ${A.traceId}`);if(A.attributes&&Object.keys(A.attributes).length>0){let t=Object.entries(A.attributes).map(([g,i])=>`${g}=${i}`).join(", ");IA(`Attributes: ${t}`)}if(A.region)IA(`Region: ${A.region}`);WB(),MA()},Dv=(A)=>{if(!A)return;let t=A.split(",").map((g)=>g.trim()).filter((g)=>g.length>0);return t.length>0?t:void 0},TqA=(A,t)=>{let g=Dv(A)?.map((o)=>o.toUpperCase());if(!g)return;let i=g.find((o)=>!KrA.includes(o));if(!i)return g;let n=`Invalid severity: ${i}. Valid values: ${KrA.join(", ")}.`;if(t)return u(n);return D(n)},JqA=(A,t)=>{return Fi({cliFlag:t,globalUrl:A.apiBaseUrl,globalDomain:A.apiDomain,buildUrlFromDomain:(g)=>`https://api.${g}`,defaultUrl:"https://api.sazabi.com"})},PqA=(A)=>{let t=(()=>{try{return new URL(A)}catch{return null}})();if(!t)return;if(!FqA(t.hostname))return;return t.protocol="http:",t.port=LqA,t.pathname="/v1/tail",t.search="",t.hash="",t.toString()},RqA=(A,t,g,i)=>{if(t)return _rA(t);if(A.tailBaseUrl)return _rA(A.tailBaseUrl);let n=PqA(i);if(n)return n;if(A.tailDomain&&g)return`https://${g}.tail.${A.tailDomain}/v1/tail`;if(g){try{let o=new URL(i).hostname;if(o.endsWith(".sazabi.dev")){let e=o.includes(".staging.")?"staging.sazabi.dev":"development.sazabi.dev";return`https://${g}.tail.${e}/v1/tail`}}catch{}return`https://${g}.tail.sazabi.com/v1/tail`}return},_rA=(A)=>{let t=A.replace(/^wss:/i,"https:").replace(/^ws:/i,"http:"),g=(()=>{try{return new URL(t)}catch{return null}})();if(!g)return t;return g.pathname="/v1/tail",g.search="",g.hash="",g.toString()},fqA=async(A)=>{if(A.regionFlag){if(!/^[a-z]+-[a-z]+-\d+$/.test(A.regionFlag))Gn(`Invalid region format: "${A.regionFlag}". Expected format: us-west-2.`),process.exit(1);return A.regionFlag}if(!A.projectId)return;return(await fb({token:A.token,projectId:A.projectId,apiBaseUrlFlag:A.apiBaseUrlFlag,jsonMode:A.jsonMode})).region};iA();uA();CA();var vqA={total:{label:"Total",type:{kind:"number"}},startDate:{label:"Start",type:{kind:"date"}},endDate:{label:"End",type:{kind:"date"}},interval:{label:"Interval",type:{kind:"string"}},series:{label:"Series",type:{kind:"custom",render:(A)=>`${Array.isArray(A)?A.length:0} series`,serialize:(A)=>A}}},OqA={layout:"field-list",schema:vqA,fields:["total","startDate","endDate","interval","series"]},zqA={group:{label:"Group",type:{kind:"string"}},total:{label:"Total",type:{kind:"number"},align:"right"},points:{label:"Points",type:{kind:"custom",render:(A)=>Array.isArray(A)?String(A.length):"0",serialize:(A)=>A},align:"right"}},mqA={schema:zqA,columns:["group","total","points"],header:{title:"Log volume",variant:"results"},emptyMessage:"No log volume found."},WqA=(A)=>{if(A==="service")return"service_name";if(A==="severity")return"severity_text";return A},ZqA=(A)=>{let t=new Date,g=JB(A),i=g.endDate??t.toISOString();return{startDate:g.startDate??new Date(new Date(i).getTime()-3600000).toISOString(),endDate:i,...A.interval?{interval:A.interval}:{},...A.groupBy?{groupBy:WqA(A.groupBy)}:{},filters:{...A.service?{service_name:A.service}:{},...A.severity?{severity_text:A.severity}:{},...A.env?{environment:A.env}:{}}}},xrA=async(A)=>{let t=R({tokenFlag:A.token,projectIdFlag:A.project,jsonMode:A.json}),g=f({token:t.token,projectId:t.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:A.json}),i=l(await g.logs.volume(ZqA(A)),"Failed to query log volume",A.json);if(A.json){W(OqA,i,{json:!0});return}VqA(i)},VqA=(A)=>{if(A.series.length>0)IA(`Total ${A.total} logs from ${A.startDate} to ${A.endDate} at ${A.interval}`);s(mqA,A.series,{count:A.series.length})};var Ia=(A,t)=>{let g=[],i=`--${t}=`;for(let n=0;n<A.length;n+=1){let o=A[n];if(o===void 0)continue;if(o===`--${t}`){let e=A[n+1];if(e!==void 0&&!e.startsWith("-"))g.push(e),n+=1;continue}if(o.startsWith(i))g.push(o.slice(i.length))}return g},qrA=nA("logs","Stream, search, and forward logs").withSubcommands({schema:L("schema","Describe the active log backend and optionally retrieve schema bundles",async(A)=>{let{values:t}=F(A,{...m,project:{type:"string"},question:{type:"string"},"top-k":{type:"string"}}),g=t["top-k"],i=typeof g==="string"&&g.length>0?Number.parseInt(g,10):void 0;if(i!==void 0&&(!Number.isFinite(i)||i<1))throw Error("--top-k must be a positive integer");let n=typeof t.question==="string"&&t.question.trim().length>0?t.question.trim():void 0,o={token:t.token,project:t.project,question:n,"top-k":i,json:t.json,"api-base-url":t["api-base-url"]};await XrA(o)}).withOptions({...z,project:{type:"string",description:"Override project ID (default: active project)"},question:{type:"string",description:"Optional natural-language question for schema-bundle retrieval"},"top-k":{type:"string",description:"Max schema bundles to return when --question is set"}}).withExamples(["sazabi logs schema --json # Backend, fields, and recent key hints",'sazabi logs schema --question "5xx errors by route" # Question-conditioned schema bundles','sazabi logs schema --question "intake batch failures" --json # Machine-readable schema bundles']).build(),tail:L("tail","Stream logs from the active project in real time",async(A)=>{let{values:t}=F(A,{...m,severities:{type:"string"},services:{type:"string"},environments:{type:"string"},search:{type:"string"},"trace-id":{type:"string"},attribute:{type:"string"},attrs:{type:"string"},duration:{type:"string"},"tail-base-url":{type:"string"},region:{type:"string"}}),g={};if(t.token)g.token=t.token;if(t.severities)g.severities=t.severities;if(t.services)g.services=t.services;if(t.environments)g.environments=t.environments;if(t.search)g.search=t.search;if(t["trace-id"])g.traceId=t["trace-id"];let i=Ia(A,"attribute");if(i.length>0)g.attribute=i;if(t.attrs)g.attrs=t.attrs;if(t.duration)g.duration=Qg(t.duration,1,Number.MAX_SAFE_INTEGER,"Duration",t.json);if(t.json)g.json=!0;if(t["tail-base-url"])g.tailBaseUrl=t["tail-base-url"];if(t.region)g.region=t.region;if(t["api-base-url"])g.apiBaseUrl=t["api-base-url"];await srA(g)}).withOptions({...z,severities:{type:"string",description:"Filter by comma-separated severities (e.g., ERROR,WARN,INFO)"},services:{type:"string",description:"Filter by comma-separated service names"},environments:{type:"string",description:"Filter by comma-separated environments"},search:{type:"string",description:"Filter by search term (case-insensitive)"},"trace-id":{type:"string",description:"Filter by trace ID"},attribute:{type:"string",description:"Filter by log attribute as key=value (exact match). Repeat for multiple attributes."},attrs:{type:"string",description:"Show log attributes in output: comma-separated keys, or 'all'"},duration:{type:"string",description:"Duration to tail in seconds (default: unlimited)"},"tail-base-url":{type:"string",description:"Override tail SSE base URL"},region:{type:"string",description:"Override project region"}}).withExamples(["sazabi logs tail # Tail all logs in real time","sazabi logs tail --severities ERROR,WARN # Tail only errors and warnings","sazabi logs tail --services api,worker # Tail specific services","sazabi logs tail --environments production,staging # Tail specific environments",'sazabi logs tail --search "database" # Tail logs matching search term',"sazabi logs tail --attribute user.id=42 # Tail logs with an exact attribute value","sazabi logs tail --attrs model,prompt # Show selected attributes per line","sazabi logs tail --attrs all # Show every attribute per line","sazabi logs tail --json # Output as JSON"]).build(),query:L("query","Search stored logs in the current project (POST /logs/query)",async(A)=>{let{values:t,positionals:g}=F(A,{...m,project:{type:"string"},limit:{type:"string"},cursor:{type:"string"},mode:{type:"string"},"sort-field":{type:"string"},"sort-direction":{type:"string"},select:{type:"string"},from:{type:"string"},to:{type:"string"},last:{type:"string"},service:{type:"string"},severity:{type:"string"},env:{type:"string"},"trace-id":{type:"string"},attribute:{type:"string"},filter:{type:"string"},"search-field":{type:"string"},"query-all":{type:"boolean"},all:{type:"boolean"}},{allowPositionals:!0}),i=g.join(" ").trim(),n=Ia(A,"filter"),o=Ia(A,"attribute"),e=Ia(A,"search-field"),I=Boolean(t.from||t.to||t.last||t.service||t.severity||t.env||t["trace-id"])||n.length>0||o.length>0;if(!i&&!t["query-all"]&&!I){if(t.json)return u("Search text, a structured filter, or --query-all is required. Usage: sazabi logs query <search-text> [options]");return D("Search text, a structured filter, or --query-all is required. Usage: sazabi logs query <search-text> [options]")}if(i.length>xb){if(t.json)return u(`Search text must be at most ${xb} characters.`);return D(`Search text must be at most ${xb} characters.`)}if(i&&t["query-all"]){if(t.json)return u("Pass either a search phrase or --query-all, not both.");return D("Pass either a search phrase or --query-all, not both.")}if(t.mode&&!i){if(t.json)return u("--mode requires search text (search is omitted).");return D("--mode requires search text (search is omitted).")}let h={token:t.token,project:t.project,json:t.json,"api-base-url":t["api-base-url"],omitSearch:t["query-all"]===!0||!i,from:t.from,to:t.to,last:t.last,service:t.service,severity:t.severity,env:t.env,traceId:t["trace-id"],attributes:o,filters:n,searchFields:e,all:t.all};if(t.limit)h.limit=Qg(t.limit,1,1000,"Limit",t.json);if(t.cursor)h.cursor=t.cursor;if(t.mode)h.mode=Hg(t.mode,["any","all","phrase"],"Mode",t.json);if(t["sort-field"])h["sort-field"]=t["sort-field"];if(t["sort-direction"]&&!t["sort-field"]){if(t.json)return u("--sort-direction requires --sort-field.");return D("--sort-direction requires --sort-field.")}if(t["sort-direction"])h["sort-direction"]=Hg(t["sort-direction"],["asc","desc"],"Sort direction",t.json);if(t.select)h.select=t.select;await HrA(i,h)}).withPositionalArgs("[search-text]").withOptions({...z,project:{type:"string",description:"Override project ID (default: active project)"},limit:{type:"string",description:"Max rows to return (1-1000, default: 50)"},cursor:{type:"string",description:"Pagination cursor from a previous response"},mode:{type:"string",description:"Token match mode: any, all, or phrase (default: all)"},"sort-field":{type:"string",description:"Field to sort by (e.g. @timestamp)"},"sort-direction":{type:"string",description:"Sort direction: asc or desc (default: desc)"},select:{type:"string",description:"Comma-separated fields to return"},from:{type:"string",description:"Start time as ISO-8601 timestamp"},to:{type:"string",description:"End time as ISO-8601 timestamp"},last:{type:"string",description:"Relative time window, for example 30m, 6h, or 7d"},service:{type:"string",description:"Filter by service name"},severity:{type:"string",description:"Filter by severity, for example ERROR"},env:{type:"string",description:"Filter by deployment environment"},"trace-id":{type:"string",description:"Filter by trace ID"},attribute:{type:"string",description:"Filter by log attribute as key=value (exact match); repeatable"},filter:{type:"string",description:"Structured filter as <field>.<op>=<value>; repeatable"},"search-field":{type:"string",description:"Restrict full-text search to a field (body, message, attributes, or attributes[<key>]); repeatable"},"query-all":{type:"boolean",description:"Omit full-text search and return the API default slice (sort/pagination only; server may require other filters)"},all:{type:"boolean",description:"Fetch all pages until the server returns no cursor"}}).withExamples(['sazabi logs query "connection refused" --last 1h --service api --severity ERROR # Search recent API errors',"sazabi logs query --trace-id abc123 --select timestamp,service,severity,body # Find logs for one trace","sazabi logs query --filter http_status_code.gte=500 --limit 100 --json # Machine-readable structured filter","sazabi logs query --attribute user.id=42 --last 1h --json # Filter by an exact attribute value",'sazabi logs query "beach house" --search-field attributes --last 1h # Full-text search inside attribute values',"sazabi logs query --query-all --select timestamp,body,attributes --json # Return the full attributes map","sazabi logs query error --mode any --limit 100 # Match any token with a larger page","sazabi logs query --query-all --limit 20 --sort-field @timestamp # Recent rows without full-text search","sazabi logs query slow --json # Machine-readable output"]).build(),patterns:L("patterns","Search normalized log patterns for discovery",async(A)=>{let{values:t,positionals:g}=F(A,{...m,project:{type:"string"},severity:{type:"string"},from:{type:"string"},to:{type:"string"},last:{type:"string"},limit:{type:"string"}},{allowPositionals:!0}),i={token:t.token,project:t.project,query:g.join(" ").trim()||void 0,severity:t.severity,from:t.from,to:t.to,last:t.last,json:t.json,"api-base-url":t["api-base-url"]};if(t.limit)i.limit=Qg(t.limit,1,100,"Limit",t.json);await VrA(i)}).withPositionalArgs("[pattern-text]").withOptions({...z,project:{type:"string",description:"Override project ID (default: active project)"},severity:{type:"string",description:"Filter by severity, for example ERROR"},from:{type:"string",description:"Start time as ISO-8601 timestamp"},to:{type:"string",description:"End time as ISO-8601 timestamp"},last:{type:"string",description:"Relative time window, for example 30m, 6h, or 7d"},limit:{type:"string",description:"Max patterns to return (1-100, default: 25)"}}).withExamples(['sazabi logs patterns "connection refused" --severity ERROR --limit 25 # Find recurring error patterns',"sazabi logs patterns --last 24h --json # Export recent patterns"]).build(),volume:L("volume","Summarize log volume by time and optional dimension",async(A)=>{let{values:t}=F(A,{...m,project:{type:"string"},from:{type:"string"},to:{type:"string"},last:{type:"string"},interval:{type:"string"},"group-by":{type:"string"},service:{type:"string"},severity:{type:"string"},env:{type:"string"}}),g={token:t.token,project:t.project,from:t.from,to:t.to,last:t.last,service:t.service,severity:t.severity,env:t.env,json:t.json,"api-base-url":t["api-base-url"]};if(t.interval)g.interval=Hg(t.interval,["1m","5m","15m","1h"],"Interval",t.json);if(t["group-by"])g.groupBy=Hg(t["group-by"],["service","severity","environment"],"Group by",t.json);await xrA(g)}).withOptions({...z,project:{type:"string",description:"Override project ID (default: active project)"},from:{type:"string",description:"Start time as ISO-8601 timestamp"},to:{type:"string",description:"End time as ISO-8601 timestamp"},last:{type:"string",description:"Relative time window, for example 30m, 6h, or 7d"},interval:{type:"string",description:"Bucket interval: 1m, 5m, 15m, or 1h"},"group-by":{type:"string",description:"Group by service, severity, or environment"},service:{type:"string",description:"Filter by service name"},severity:{type:"string",description:"Filter by severity, for example ERROR"},env:{type:"string",description:"Filter by deployment environment"}}).withExamples(["sazabi logs volume --last 6h --group-by service # Compare service log volume","sazabi logs volume --last 24h --severity ERROR --interval 15m --json # Export error volume"]).build(),"native-query":L("native-query","Run a backend-native read-only log query",async(A)=>{let{values:t}=F(A,{...m,project:{type:"string"},query:{type:"string"},file:{type:"string",short:"f"}}),g={token:t.token,project:t.project,query:t.query,file:t.file,json:t.json,"api-base-url":t["api-base-url"]};await WrA(g)}).withOptions({...z,project:{type:"string",description:"Override project ID (default: active project)"},query:{type:"string",description:"Backend-native query text"},file:{type:"string",short:"f",description:"Read backend-native query text from a file"}}).withExamples(['sazabi logs native-query --query "SELECT service_name, count() FROM log_volume_per_minute GROUP BY service_name LIMIT 20" # Run backend-native query text',"sazabi logs native-query --file investigation.sql --json # Run a query from a file"]).build(),forward:L("forward","Forward plaintext logs to the active project",async(A)=>{let{values:t}=F(A,{...m,file:{type:"string",short:"f"},follow:{type:"boolean"},"batch-size":{type:"string"},"intake-base-url":{type:"string"},"public-key":{type:"string"},service:{type:"string"},attribute:{type:"string"},region:{type:"string"}}),g={};if(t.token)g.token=t.token;if(t.file)g.file=t.file;if(t.follow)g.follow=t.follow;if(t["batch-size"])g.batchSize=Qg(t["batch-size"],1,Number.MAX_SAFE_INTEGER,"Batch size",t.json);if(t["api-base-url"])g.apiBaseUrl=t["api-base-url"];if(t["intake-base-url"])g.intakeBaseUrl=t["intake-base-url"];if(t.region)g.region=t.region;if(t["public-key"])g.publicKey=t["public-key"];if(t.service)g.service=t.service;let i=Ia(A,"attribute");if(i.length>0)g.attributes=i;await mrA({...g,json:t.json})}).withOptions({...z,json:{type:"boolean",description:"Output a final JSON summary"},file:{type:"string",short:"f",description:"Read from file instead of stdin"},follow:{type:"boolean",description:"Follow file for new lines (like tail -f)"},"batch-size":{type:"string",description:"Number of logs to batch before sending (default: 100)"},"intake-base-url":{type:"string",description:"Override intake base URL"},"public-key":{type:"string",description:"Use this public key value (skip creating/storing)"},service:{type:"string",description:"Set OTLP service.name for forwarded lines (default: sazabi-cli)"},attribute:{type:"string",description:"Attach a log attribute as key=value. Repeat for multiple attributes."},region:{type:"string",description:"Override project region"}}).withExamples(['echo "Log message" | sazabi logs forward # Forward from stdin',"sazabi logs forward --file app.log # Forward from file","sazabi logs forward --file app.log --follow # Forward file with tail -f behavior","sazabi logs forward --file app.log --batch-size 50 # Forward with custom batch size"]).build()}).withExamples(["sazabi logs tail # Tail all logs in real time","sazabi logs tail --severities ERROR,WARN # Tail only errors and warnings",'sazabi logs query "timeout" # Search stored logs',"sazabi logs forward --file app.log # Forward from file"]).build();iA();uA();CA();var drA={connectionId:{label:"ID",type:{kind:"string"}},connectionKey:{label:"Key",type:{kind:"string"}},url:{label:"URL",type:{kind:"string"}},providerId:{label:"Provider",type:{kind:"string"}},displayName:{label:"Name",type:{kind:"string"}},source:{label:"Source",type:{kind:"string"}},installStatus:{label:"Status",type:{kind:"string"}},authMode:{label:"Auth",type:{kind:"string"}},transport:{label:"Transport",type:{kind:"string"}},serverUrl:{label:"Server URL",type:{kind:"string"}},readOnly:{label:"Read-only",type:{kind:"boolean"}},enabledToolCount:{label:"Enabled tools",type:{kind:"number"}},connectedAt:{label:"Connected",type:{kind:"nullable-date"}},createdAt:{label:"Created",type:{kind:"date"}},updatedAt:{label:"Updated",type:{kind:"date"}}},jqA={schema:drA,columns:["connectionId","providerId","displayName","installStatus","enabledToolCount","url"],header:"MCP connectors",emptyMessage:"No MCP connectors configured. Add one in Settings > MCP connectors in the dashboard."},db={layout:"field-list",schema:drA,fields:["connectionId","connectionKey","providerId","displayName","source","installStatus","authMode","transport","serverUrl","url","readOnly","enabledToolCount","connectedAt","createdAt","updatedAt"],title:"MCP connector"},HqA={name:{label:"Name",type:{kind:"string"}},title:{label:"Title",type:{kind:"string"}},description:{label:"Description",type:{kind:"string"}},isReadOnly:{label:"Read-only",type:{kind:"boolean"}},enabled:{label:"Enabled",type:{kind:"boolean"}}},XqA={schema:HqA,columns:["name","title","isReadOnly","enabled"],header:"Tools",emptyMessage:"No tools discovered for this connector."},KqA={providerId:{label:"Provider",type:{kind:"string"}},label:{label:"Name",type:{kind:"string"}},authMode:{label:"Auth",type:{kind:"string"}},availability:{label:"Availability",type:{kind:"string"}},hasSetupSkill:{label:"Setup skill",type:{kind:"boolean"}}},_qA={schema:KqA,columns:["providerId","label","authMode","availability","hasSetupSkill"],header:"MCP connector providers",emptyMessage:"No MCP connector providers found."},sqA={providerId:{label:"Provider",type:{kind:"string"}},setupSkill:{label:"Setup skill",type:{kind:"string"}}},xqA={layout:"field-list",schema:sqA,fields:["providerId","setupSkill"],title:"MCP connector setup skill"},ce=(A)=>{let t=A.json,g=R({tokenFlag:A.token,jsonMode:t});return{client:f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:t}),json:t,projectId:g.projectId}},ha=(A,t)=>({...A,url:PCA(t,A.connectionId)}),qqA=3000,dqA=async(A)=>{let{values:t}=F(A,{...m,"project-id":{type:"string"},"connected-only":{type:"boolean"}}),{client:g,json:i,projectId:n}=ce(t),{connectors:o}=l(await g.mcpConnectors.list({projectId:t["project-id"],connectedOnly:t["connected-only"]}),"Couldn't list MCP connectors (check the active project and try again)",i),e=$n(t["project-id"]??n,i);s(jqA,o.map((I)=>ha(I,e)),{json:i})},pqA=async(A)=>{let{values:t,positionals:g}=F(A,{...m,"project-id":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Connection ID is required.");return D("Connection ID is required.")}let{client:n,json:o,projectId:e}=ce(t),{connector:I}=l(await n.mcpConnectors.get({connectionId:i,projectId:t["project-id"]}),"Couldn't get MCP connector (run 'sazabi mcp-connectors list' to see connection IDs)",o),h=$n(t["project-id"]??e,o);W(db,ha(I,h),{json:o})},AdA=async(A)=>{let{values:t,positionals:g}=F(A,{...m,"project-id":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Connection ID is required.");return D("Connection ID is required.")}let{client:n,json:o,projectId:e}=ce(t),{connector:I,tools:h}=l(await n.mcpConnectors.details({connectionId:i,projectId:t["project-id"]}),"Couldn't inspect MCP connector (run 'sazabi mcp-connectors list' to see connection IDs)",o),B=$n(t["project-id"]??e,o),c=ha(I,B);if(o){X({connector:c,tools:h});return}W(db,c,{json:o}),s(XqA,h,{json:o})},tdA=async(A)=>{let{values:t}=F(A,{...m}),{client:g,json:i}=ce(t),{providers:n}=l(await g.mcpConnectors.listProviders(),"Couldn't list MCP connector providers (try again)",i),o=n.map((e)=>({providerId:e.providerId,label:e.label,authMode:e.authMode,availability:e.availability,hasSetupSkill:Boolean(e.setupSkill)}));s(_qA,o,{json:i})},gdA=async(A)=>{let{values:t}=F(A,{...m,"provider-id":{type:"string"}});if(!t["provider-id"]){if(t.json)return u("--provider-id is required.");return D("--provider-id is required. Use 'sazabi mcp-connectors providers' to see valid provider IDs.")}let{client:g,json:i}=ce(t),{providers:n}=l(await g.mcpConnectors.listProviders(),"Couldn't list MCP connector providers (try again)",i),o=n.find((e)=>e.providerId===t["provider-id"]);if(!o){let e=`Unknown MCP connector provider: '${t["provider-id"]}'. Run 'sazabi mcp-connectors providers' to see valid provider IDs.`;if(i)return u(e);return D(e)}if(!o.setupSkill){if(i)return u(`No setup skill available for ${t["provider-id"]}.`);return D(`No setup skill available for ${t["provider-id"]}. This MCP connector does not have an agent-ready skill yet.`)}W(xqA,{providerId:t["provider-id"],setupSkill:o.setupSkill},{json:i})},ndA=async(A)=>{let{values:t,positionals:g}=F(A,{...m,"project-id":{type:"string"},"server-url":{type:"string"},scopes:{type:"string"},"read-only":{type:"boolean"}},{allowPositionals:!0}),i=t.json,n=g[0];if(!n){if(i)return u("Provider ID is required. Run 'sazabi mcp-connectors providers' to see available providers.");return D("Provider ID is required. Run 'sazabi mcp-connectors providers' to see available providers.")}let{client:o,projectId:e}=ce(t),I=t.scopes,h=I?I.split(",").map((C)=>C.trim()).filter(Boolean):void 0,B=l(await o.mcpConnectors.beginOAuthInstall({providerId:n,projectId:t["project-id"],serverUrl:t["server-url"],requestedScopes:h,readOnly:t["read-only"]}),`Couldn't start the OAuth install flow for '${n}'`,i);if(i){X({authorizationUrl:B.authorizationUrl,connectionId:B.connectionId,expiresAt:B.expiresAt});return}JA(`Connect ${n}`),IA("Complete the authorization in a browser where you're signed in to the Sazabi dashboard."),IA(`Opening ${jA.info(B.authorizationUrl)}`),YB(B.authorizationUrl),IA("Waiting for the browser flow to complete...");let c=new Date(B.expiresAt).getTime()+15000;while(Date.now()<c){await $B(qqA);let C=l(await o.mcpConnectors.getOAuthInstallAttempt({connectionId:B.connectionId,projectId:t["project-id"]}),"Couldn't poll the install attempt (try again)",i);if(C.status==="authorizing")continue;if(C.status==="connected"){if(C.connector){x(`Connected ${C.connector.displayName}.`);let r=$n(t["project-id"]??e,i);W(db,ha(C.connector,r),{json:i})}else x(`Connected ${n}.`);return}return D(`Connect failed. The provider returned an error. Run 'sazabi mcp-connectors connect ${n}' again.`)}return D("The browser flow didn't complete in time. Run the command again.")},idA=async(A)=>{let{values:t,positionals:g}=F(A,{...m,"project-id":{type:"string"}},{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return u("Connection ID is required.");return D("Connection ID is required. Run 'sazabi mcp-connectors list' to see connection IDs.")}let{client:o}=ce(t);if(l(await o.mcpConnectors.disconnect({connectionId:i,projectId:t["project-id"]}),"Couldn't disconnect the MCP connector",n),n){X({success:!0});return}x("MCP connector disconnected.")},odA=async(A)=>{let{values:t,positionals:g}=F(A,{...m,"project-id":{type:"string"},"server-url":{type:"string"},transport:{type:"string"},headers:{type:"string"},"aws-sig-v4":{type:"string"}},{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return u("Connection ID is required.");return D("Connection ID is required. Run 'sazabi mcp-connectors list' to see connection IDs.")}let o=t["server-url"],e=t.transport,I,h=t.headers;if(h)try{let w=JSON.parse(h);if(!Array.isArray(w))throw Error("not an array");I=w}catch{if(n)return u(`--headers must be a JSON array, e.g. '[{"id":"auth","name":"Authorization","value":"Bearer ..."}]'`);return D(`--headers must be a JSON array, e.g. '[{"id":"auth","name":"Authorization","value":"Bearer ..."}]'`)}let B,c=t["aws-sig-v4"];if(c)try{let w=JSON.parse(c);if(typeof w!=="object"||w===null||Array.isArray(w))throw Error("not an object");B=w}catch{if(n)return u(`--aws-sig-v4 must be a JSON object, e.g. '{"accessKeyId":"...","secretAccessKey":"...","region":"us-east-1"}'`);return D(`--aws-sig-v4 must be a JSON object, e.g. '{"accessKeyId":"...","secretAccessKey":"...","region":"us-east-1"}'`)}if(!o&&!e&&!I&&!B){if(n)return u("At least one of --server-url, --transport, --headers, or --aws-sig-v4 is required.");return D("At least one of --server-url, --transport, --headers, or --aws-sig-v4 is required.")}let{client:C,projectId:r}=ce(t),{connector:a}=l(await C.mcpConnectors.update({connectionId:i,projectId:t["project-id"],...o?{serverUrl:o}:{},...e?{transport:e}:{},...I?{headers:I}:{},...B?{awsSigV4:B}:{}}),"Couldn't update the MCP connector (check the values and try again)",n);if(!n)x("MCP connector updated.");let y=$n(t["project-id"]??r,n);W(db,ha(a,y),{json:n})},prA=nA("mcp-connectors","Inspect MCP connectors").withSubcommands({list:L("list","List configured MCP connectors",dqA).withOptions({...z,"project-id":{type:"string",description:"Project ID"},"connected-only":{type:"boolean",description:"Only show connected connectors"}}).withExamples(["sazabi mcp-connectors list # List all connectors","sazabi mcp-connectors list --connected-only # Only connected ones","sazabi mcp-connectors list --json # Output as JSON"]).build(),get:L("get","Get one MCP connector",pqA).withPositionalArgs("<connection-id>").withOptions({...z,"project-id":{type:"string",description:"Project ID"}}).withExamples(["sazabi mcp-connectors get <id> # Show connector details"]).build(),details:L("details","Inspect one connector's tool surface",AdA).withPositionalArgs("<connection-id>").withOptions({...z,"project-id":{type:"string",description:"Project ID"}}).withExamples(["sazabi mcp-connectors details <id> # Show enabled tools","sazabi mcp-connectors details <id> --json # Output as JSON"]).build(),providers:L("providers","List all supported MCP connector providers",tdA).withOptions({...z}).withExamples(["sazabi mcp-connectors providers # List all providers","sazabi mcp-connectors providers --json # Output as JSON"]).build(),skill:L("skill","Show setup skill for an MCP connector provider",gdA).withOptions({...z,"provider-id":{type:"string",description:"MCP connector provider ID (e.g. linear, supabase)"}}).withExamples(["sazabi mcp-connectors skill --provider-id linear # Show Linear setup skill","sazabi mcp-connectors skill --provider-id posthog # Show PostHog setup skill","sazabi mcp-connectors skill --provider-id x --json # Output as JSON"]).build(),connect:L("connect","Connect an MCP provider via an OAuth browser flow",ndA).withPositionalArgs("<provider-id>").withOptions({...z,"project-id":{type:"string",description:"Project to install the connector into"},"server-url":{type:"string",description:"Server URL for multi-region providers (defaults to the provider primary)"},scopes:{type:"string",description:"Comma-separated OAuth scopes to request (defaults to provider recommended set)"},"read-only":{type:"boolean",description:"Restrict the connector to read-only tools after install"}}).withExamples(["sazabi mcp-connectors connect linear # Connect Linear via OAuth","sazabi mcp-connectors connect slack --read-only # Read-only Slack connector","sazabi mcp-connectors connect linear --json # Return auth URL as JSON"]).build(),disconnect:L("disconnect","Disconnect an MCP connector",idA).withPositionalArgs("<connection-id>").withOptions({...z,"project-id":{type:"string",description:"Project ID"}}).withExamples(["sazabi mcp-connectors disconnect <id> # Remove the connector"]).build(),"update-credentials":L("update-credentials","Update a custom connector's server URL, transport, or headers",odA).withPositionalArgs("<connection-id>").withOptions({...z,"project-id":{type:"string",description:"Project ID"},"server-url":{type:"string",description:"New MCP server URL"},transport:{type:"string",description:"New transport protocol (sse | streamable-http | stdio)"},headers:{type:"string",description:`Replacement header set as JSON array, e.g. '[{"id":"auth","name":"Authorization","value":"Bearer ..."}]'`},"aws-sig-v4":{type:"string",description:`AWS SigV4 credentials as JSON, e.g. '{"accessKeyId":"...","secretAccessKey":"...","region":"us-east-1"}'`}}).withExamples(["sazabi mcp-connectors update-credentials <id> --server-url https://new.example.com/mcp # Update server URL",`sazabi mcp-connectors update-credentials <id> --headers '[{"id":"auth","name":"Authorization","value":"Bearer ..."}]' # Replace headers`]).build()}).withExamples(["sazabi mcp-connectors list # List configured MCP connectors","sazabi mcp-connectors get <id> # Inspect one connector","sazabi mcp-connectors details <id> # Inspect a connector's tool surface","sazabi mcp-connectors providers # List all MCP connector providers","sazabi mcp-connectors connect linear # Connect Linear via OAuth","sazabi mcp-connectors disconnect <id> # Remove a connector","sazabi mcp-connectors update-credentials <id> --server-url https://... # Update server URL","sazabi mcp-connectors skill --provider-id linear # Show setup skill"]).build();iA();uA();CA();var AaA={membershipId:{label:"Membership ID",type:{kind:"string"}},userId:{label:"User ID",type:{kind:"string"}},name:{label:"Name",type:{kind:"nullable-string"}},email:{label:"Email",type:{kind:"string"}},role:{label:"Role",type:{kind:"string"}}},edA={schema:AaA,columns:["membershipId","userId","name","email","role"],header:"Members",emptyMessage:"No members found."},QdA={layout:"field-list",schema:AaA,fields:["membershipId","userId","name","email","role"]},IdA={id:{label:"ID",type:{kind:"string"}},email:{label:"Email",type:{kind:"string"}},role:{label:"Role",type:{kind:"string"}},status:{label:"Status",type:{kind:"string"}},expiresAt:{label:"Expires",type:{kind:"string"}}},taA={schema:IdA,columns:["id","email","role","status","expiresAt"],header:"Invitations",emptyMessage:"No pending invitations."},hdA=async(A)=>{let t=R({tokenFlag:A.token,organizationIdFlag:A.organizationId,jsonMode:A.json}),g=f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=l(await g.members.list({organizationId:t.organizationId}),"Couldn't list members (check the active organization and try again)",A.json);s(edA,i.members,{json:A.json})},BdA=async(A,t)=>{let g=R({tokenFlag:t.token,organizationIdFlag:t.organizationId,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.members.updateRole(A,t.role,g.organizationId),"Failed to update member role",t.json);W(QdA,n.member,{json:t.json})},cdA=async(A,t)=>{let g=R({tokenFlag:t.token,organizationIdFlag:t.organizationId,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.members.remove(A,g.organizationId),"Failed to remove member",t.json);if(t.json){X(n);return}x(`Member ${n.removedUserId} removed from the active organization.`)},CdA=async(A)=>{let t=R({tokenFlag:A.token,organizationIdFlag:A.organizationId,jsonMode:A.json}),g=f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=[];for(let n of A.emails){let o=l(await g.members.invite({email:n,role:A.role,organizationId:t.organizationId}),`Failed to invite ${n}`,A.json);i.push(o.invitation)}s(taA,i,{json:A.json})},rdA=async(A)=>{let t=R({tokenFlag:A.token,organizationIdFlag:A.organizationId,jsonMode:A.json}),g=f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=l(await g.members.listInvitations(t.organizationId),"Couldn't list invitations (check the active organization and try again)",A.json);s(taA,i.invitations,{json:A.json})},adA=async(A,t)=>{let g=R({tokenFlag:t.token,organizationIdFlag:t.organizationId,jsonMode:t.json}),i=f({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=l(await i.members.revokeInvitation({invitationId:A,organizationId:g.organizationId}),"Failed to revoke invitation",t.json);if(t.json){X(n);return}x(`Invitation ${n.revokedInvitationId} revoked.`)},gaA=nA("members","Manage organization members").withSubcommands({list:L("list","List members in the active organization",async(A)=>{let{values:t,positionals:g}=F(A,{token:{type:"string"},"organization-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0});if(g.length>0){let i=g.join(", ");if(t.json)return u(`Unexpected arguments: ${i}. Run 'sazabi members -h' for usage.`);return D(`Unexpected arguments: ${i}. Run 'sazabi members -h' for usage.`)}await hdA({token:t.token,organizationId:t["organization-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi members list # List members in the active organization"]).build(),"update-role":L("update-role","Update one member's organization role",async(A)=>{let{values:t,positionals:g}=F(A,{token:{type:"string"},"organization-id":{type:"string"},role:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("User ID is required.");return D("User ID is required.")}if(t.role!=="admin"&&t.role!=="member"){if(t.json)return u("Role must be either 'admin' or 'member'.");return D("Role must be either 'admin' or 'member'.")}await BdA(i,{token:t.token,organizationId:t["organization-id"],role:t.role,json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},role:{type:"string",description:"New role: admin or member"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi members update-role user_123 --role admin # Promote a member to admin"]).build(),remove:L("remove","Remove one member from the active organization",async(A)=>{let{values:t,positionals:g}=F(A,{token:{type:"string"},"organization-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("User ID is required.");return D("User ID is required.")}await cdA(i,{token:t.token,organizationId:t["organization-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi members remove user_123 # Remove a member by user ID","sazabi members remove alex@example.com # Remove a member by email"]).build(),invite:L("invite","Invite one or more people to the active organization by email",async(A)=>{let{values:t,positionals:g}=F(A,{token:{type:"string"},"organization-id":{type:"string"},email:{type:"string",multiple:!0},role:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0});if(g.length>0){let e=`Unexpected arguments: ${g.join(", ")}. Pass emails with --email. Run 'sazabi members -h' for usage.`;if(t.json)return u(e);return D(e)}let i=t.email??[];if(i.length===0){if(t.json)return u("At least one --email is required.");return D("At least one --email is required.")}let n=t.role??"member";if(n!=="admin"&&n!=="member"){if(t.json)return u("Role must be either 'admin' or 'member'.");return D("Role must be either 'admin' or 'member'.")}await CdA({emails:i,role:n,token:t.token,organizationId:t["organization-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},email:{type:"string",description:"Email address to invite (repeatable)"},role:{type:"string",description:"Role to grant: admin or member (default member)"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi members invite --email alex@example.com # Invite one person as a member","sazabi members invite --email a@example.com --email b@example.com --role admin # Invite several as admins"]).build(),"list-invitations":L("list-invitations","List pending invitations in the active organization",async(A)=>{let{values:t,positionals:g}=F(A,{token:{type:"string"},"organization-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0});if(g.length>0){let i=g.join(", ");if(t.json)return u(`Unexpected arguments: ${i}. Run 'sazabi members -h' for usage.`);return D(`Unexpected arguments: ${i}. Run 'sazabi members -h' for usage.`)}await rdA({token:t.token,organizationId:t["organization-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi members list-invitations # List pending invitations"]).build(),"revoke-invitation":L("revoke-invitation","Revoke one pending invitation in the active organization",async(A)=>{let{values:t,positionals:g}=F(A,{token:{type:"string"},"organization-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return u("Invitation ID is required.");return D("Invitation ID is required.")}await adA(i,{token:t.token,organizationId:t["organization-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi members revoke-invitation invitation_123 # Revoke a pending invitation"]).build()}).withExamples(["sazabi members list # List members in the active organization","sazabi members invite --email alex@example.com # Invite a person by email","sazabi members update-role user_123 --role admin # Promote a member to admin","sazabi members remove alex@example.com # Remove a member by user ID or email","sazabi members list-invitations # List pending invitations","sazabi members revoke-invitation invitation_123 # Revoke a pending invitation"]).build();iA();$Q();import{readFile as EdA}from"node:fs/promises";uA();CA();var ydA=/^(\d+)(s|m|h|d)$/u,bv=(A)=>({id:A.id,projectId:A.projectId,kind:A.kind,managed:A.managed,path:A.path,title:A.title,contentHash:A.contentHash,body:"body"in A?A.body:null,createdAt:A.createdAt,updatedAt:A.updatedAt}),naA=(A)=>({documentId:A.documentId,kind:A.kind,managed:A.managed,path:A.path,title:A.title,snippet:A.snippet,score:A.score}),QaA={id:{label:"ID",type:{kind:"id"}},projectId:{label:"Project ID",type:{kind:"id"}},kind:{label:"Kind",type:{kind:"string"}},managed:{label:"Managed",type:{kind:"boolean"}},path:{label:"Path",type:{kind:"nullable-string"}},title:{label:"Title",type:{kind:"nullable-string"}},contentHash:{label:"Content hash",type:{kind:"string"}},body:{label:"Body",type:{kind:"custom",render:(A)=>A?String(A):"(empty)",serialize:(A)=>A}},createdAt:{label:"Created at",type:{kind:"date"}},updatedAt:{label:"Updated at",type:{kind:"date"}}},wdA={documentId:{label:"Document ID",type:{kind:"id"}},kind:{label:"Kind",type:{kind:"string"}},managed:{label:"Managed",type:{kind:"boolean"}},path:{label:"Path",type:{kind:"nullable-string"}},title:{label:"Title",type:{kind:"nullable-string"}},snippet:{label:"Snippet",type:{kind:"string"}},score:{label:"Score",type:{kind:"number"}}},DdA={schema:QaA,columns:["path","kind","title","updatedAt"],jsonFields:["id","projectId","kind","managed","path","title","updatedAt"],header:"Memory",emptyMessage:"No memory documents found."},IaA={layout:"field-list",schema:QaA,fields:["id","projectId","kind","managed","path","title","contentHash","body","createdAt","updatedAt"],title:"Memory document"},udA={schema:wdA,columns:["path","kind","snippet","score"],jsonFields:["documentId","kind","managed","path","title","snippet","score"],header:"Memory search results",emptyMessage:"No matching memory documents found."},Ca=(A)=>{let t=R({tokenFlag:A.token,projectIdFlag:A.projectId,jsonMode:A.json});return{client:f({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json})}},bdA=async()=>{let A=[];process.stdin.setEncoding("utf8");for await(let t of process.stdin)A.push(String(t));return A.join("")},uv=(A)=>{let t=A.join("/").trim();return t.length>0?t:void 0},ldA=(A,t)=>{if(!ydA.test(A.trim())){if(t){u("Duration must use s, m, h, or d units, for example 7d or 30m.");return}D("Duration must use s, m, h, or d units, for example 7d or 30m.");return}return A.trim()},NdA=(A,t)=>{if(A===void 0)return;try{return Vr.parse(A),A.trim()}catch{if(t){u("Kind filter must be a comma-separated list of note, runbook, or change.");return}D("Kind filter must be a comma-separated list of note, runbook, or change.");return}},UdA=(A,t)=>{if(A===void 0)return;let g=A.trim().toLowerCase();if(g==="true")return!0;if(g==="false")return!1;let i='Invalid --managed value. Expected "true" or "false".';if(t){u(i);return}D(i);return},LdA=async(A,t)=>{let g=A.body!==void 0,i=A.file!==void 0;if(g&&i){if(A.json){u("Provide memory body via exactly one of --body or --file.");return}D("Provide memory body via exactly one of --body or --file.");return}if(!g&&!i){if(!t)return;let o="Memory body is required. Provide --body <text> or --file <path>.";if(A.json){u(o);return}D(o);return}if(g)return A.body;let n=A.file;try{return n==="-"?await bdA():await EdA(n,"utf8")}catch(o){let e=`Couldn't read memory body (check that the --file path exists and is readable): ${o instanceof Error?o.message:String(o)}`;if(A.json){u(e);return}D(e);return}},haA=(A)=>({...A.kind!==void 0?{kind:A.kind}:{},...A.since!==void 0?{since:A.since}:{},...A.pathPrefix!==void 0?{pathPrefix:A.pathPrefix}:{},...A.managed!==void 0?{managed:A.managed}:{},...A.service!==void 0?{service:A.service}:{}}),SdA=async(A)=>{let{client:t}=Ca(A),g=l(await t.memory.list({...haA(A),...A.limit!==void 0?{limit:A.limit}:{},...A.cursor!==void 0?{cursor:A.cursor}:{}}),"Couldn't list memory (check the active project and try again)",A.json);s(DdA,g.documents.map(bv),{json:A.json,nextCursor:g.nextCursor})},FdA=async(A)=>{let{client:t}=Ca(A),g=l(await t.memory.get({...A.id!==void 0?{id:A.id}:{},...A.path!==void 0?{path:A.path}:{}}),"Couldn't get memory document (run 'sazabi memory list' to see paths)",A.json);W(IaA,bv(g.document),{json:A.json})},MdA=async(A)=>{let{client:t}=Ca(A),g=l(await t.memory.search({query:A.query,...haA(A),...A.limit!==void 0?{limit:A.limit}:{}}),"Couldn't search memory (check the active project and try again)",A.json);if(A.json){X({hits:g.hits.map(naA),emptyVerdict:g.emptyVerdict});return}s(udA,g.hits.map(naA),{json:!1})},kdA=async(A)=>{let t=await LdA(A,!0);if(t===void 0)return;let{client:g}=Ca(A),i=l(await g.memory.put({path:A.path,body:t,kind:A.kind??"note",...A.title!==void 0?{title:A.title}:{}}),"Couldn't write memory document (check the path and body, then try again)",A.json);if(!A.json){let n=i.document.path??i.document.id;x(`Memory document "${n}" saved.`)}W(IaA,bv(i.document),{json:A.json})},YdA=async(A)=>{let{client:t}=Ca(A);if(l(await t.memory.delete({...A.id!==void 0?{id:A.id}:{},...A.path!==void 0?{path:A.path}:{}}),"Couldn't delete memory document (run 'sazabi memory list' to see paths)",A.json),A.json){X({deleted:!0,...A.id!==void 0?{id:A.id}:{},...A.path!==void 0?{path:A.path}:{}});return}let g=A.path??A.id??"document";x(`Memory document "${g}" deleted.`)},Ba={...m,"project-id":{type:"string"}},ca={...z,"project-id":{type:"string",description:"Override active project ID"}},iaA={kind:{type:"string"},since:{type:"string"},"path-prefix":{type:"string"},managed:{type:"string"},service:{type:"string"}},oaA={kind:{type:"string",description:"Comma-separated kinds: note, runbook, or change"},since:{type:"string",description:"Only documents updated within this window, for example 7d"},"path-prefix":{type:"string",description:"Filter to paths starting with this prefix"},managed:{type:"string",description:'Filter managed documents: "true" or "false"'},service:{type:"string",description:"Filter to documents whose attrs.services contains this value"}},$dA=(A,t)=>{if(A===void 0)return;let g=Number(A);if(!Number.isInteger(g)||g<1||g>100){if(t){u("Invalid --limit value. Expected an integer between 1 and 100.");return}D("Invalid --limit value. Expected an integer between 1 and 100.");return}return g},GdA=(A,t)=>{if(A===void 0)return;let g=Number(A);if(!Number.isInteger(g)||g<1||g>50){if(t){u("Invalid --limit value. Expected an integer between 1 and 50.");return}D("Invalid --limit value. Expected an integer between 1 and 50.");return}return g},eaA=(A)=>{let t=NdA(A.kind,A.json);if(A.kind!==void 0&&t===void 0)return;let g;if(A.since!==void 0){if(g=ldA(A.since,A.json),g===void 0)return}let i=UdA(A.managed,A.json);if(A.managed!==void 0&&i===void 0)return;return{kind:t,since:g,pathPrefix:A["path-prefix"],managed:i,service:A.service}},TdA=(A,t)=>{if(A===void 0)return;if(A==="note"||A==="runbook")return A;let g='Invalid --kind value. Expected "note" or "runbook".';if(t){u(g);return}D(g);return},BaA=nA("memory","Read, search, and update durable project memory").withSubcommands({list:L("list","List project memory catalog rows",async(A)=>{let{values:t}=F(A,{...Ba,...iaA,limit:{type:"string"},cursor:{type:"string"}}),g=eaA(t);if(g===void 0)return;let i=$dA(t.limit,t.json);if(t.limit!==void 0&&i===void 0)return;await SdA({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],...g,limit:i,cursor:t.cursor})}).withOptions({...ca,...oaA,limit:{type:"string",description:"Maximum number of documents to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from previous response"}}).withExamples(["sazabi memory list # List project memory","sazabi memory list --kind note,runbook # Filter by kind","sazabi memory list --kind change --since 7d --path-prefix services/durable-agent # Recent durable-agent changes","sazabi memory list --service intake --limit 50 --json # List intake-tagged docs as JSON","sazabi memory list --managed false # List user-managed docs only"]).build(),get:L("get","Get one project memory document (prefer --json for agents)",async(A)=>{let{values:t,positionals:g}=F(A,{...Ba,id:{type:"string"}},{allowPositionals:!0}),i=uv(g);if(t.id!==void 0===(i!==void 0)){if(t.json)return u("Provide exactly one of a path or --id.");return D("Provide exactly one of a path or --id.")}await FdA({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],id:t.id,path:i})}).withPositionalArgs("[path]").withOptions({...ca,id:{type:"string",description:"Document id"}}).withExamples(["sazabi memory get AGENTS.md # Get by curated path","sazabi memory get notes/architecture.md --json # Get one document as JSON","sazabi memory get --id 22222222-2222-4222-8222-222222222222 # Get by document id"]).build(),search:L("search","Search project memory documents",async(A)=>{let{values:t,positionals:g}=F(A,{...Ba,...iaA,limit:{type:"string"}},{allowPositionals:!0}),i=g.join(" ").trim();if(!i){if(t.json)return u("Search query is required.");return D("Search query is required.")}let n=eaA(t);if(n===void 0)return;let o=GdA(t.limit,t.json);if(t.limit!==void 0&&o===void 0)return;await MdA({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],query:i,...n,limit:o})}).withPositionalArgs("<query>").withOptions({...ca,...oaA,limit:{type:"string",description:"Maximum number of hits to return (default: 10, max: 50)"}}).withExamples(['sazabi memory search "where is llm-config wired" --kind change --json # Search recent changes','sazabi memory search "known benign noise" --kind note,runbook # Search curated guidance','sazabi memory search "pooler timeout" --since 30d --service api # Search api-tagged docs','sazabi memory search "pooler timeout" --managed true --kind change # Search managed changes']).build(),put:L("put","Create or replace a curated memory document",async(A)=>{let{values:t,positionals:g}=F(A,{...Ba,body:{type:"string"},file:{type:"string"},kind:{type:"string"},title:{type:"string"}},{allowPositionals:!0}),i=uv(g);if(!i){if(t.json)return u("Memory path is required.");return D("Memory path is required.")}let n=TdA(t.kind,t.json);if(t.kind!==void 0&&n===void 0)return;await kdA({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],path:i,body:t.body,file:t.file,kind:n,title:t.title})}).withPositionalArgs("<path>").withOptions({...ca,body:{type:"string",description:"Document body text"},file:{type:"string",description:"Read document body from a file, or '-' for stdin"},kind:{type:"string",description:'Curated kind: "note" (default) or "runbook"'},title:{type:"string",description:"Optional display title"}}).withExamples(["sazabi memory put AGENTS.md --file ./AGENTS.md # Upsert from a local file",'sazabi memory put notes/customer-context.md --body "…" --kind note # Upsert inline note body']).build(),delete:L("delete","Delete a curated memory document",async(A)=>{let{values:t,positionals:g}=F(A,{...Ba,id:{type:"string"}},{allowPositionals:!0}),i=uv(g);if(t.id!==void 0===(i!==void 0)){if(t.json)return u("Provide exactly one of a path or --id.");return D("Provide exactly one of a path or --id.")}await YdA({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],id:t.id,path:i})}).withPositionalArgs("[path]").withOptions({...ca,id:{type:"string",description:"Document id"}}).withExamples(["sazabi memory delete notes/stale.md # Delete a curated document"]).build()}).withExamples(["sazabi memory get AGENTS.md # Get the index doc","sazabi memory list --kind note,runbook # Browse curated docs",'sazabi memory search "pooler timeout" --since 30d # Semantic search',"sazabi memory put AGENTS.md --file ./AGENTS.md # Upsert a curated doc","sazabi memory delete notes/stale.md # Delete a curated doc"]).build();iA();uA();CA();iA();uA();CA();CA();var JdA=2000,pb=async(A)=>{let t=A.pollIntervalMs??JdA,g=Date.now(),i=!1,n={completed:!1,threadId:A.threadId,runId:A.runId,status:"processing",response:null};while(!0){let o=await A.client.runs.get(A.runId);if(!o.success){if(!RdA(o))return lv(A.printProgress,i),o}else if(n=o.value,o.value.completed)return lv(A.printProgress,i),o;if(A.timeoutMs!==void 0&&Date.now()-g>=A.timeoutMs)return lv(A.printProgress,i),Zt(n);i=PdA(A.printProgress,i),await Qa(t)}},PdA=(A,t)=>{if(!A)return t;if(!t)process.stdout.write(`
8755
8755
  `);return process.stdout.write("."),!0},lv=(A,t)=>{if(!A||!t)return;process.stdout.write(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sazabi/cli",
3
- "version": "0.24.0",
3
+ "version": "0.25.0-dev.gac76330",
4
4
  "description": "The Sazabi CLI",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",