@sazabi/cli 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -394,7 +394,7 @@ If enforced, the user must use Workload Identity Federation instead (manual setu
394
394
  ### Key works but Sazabi shows "cannot access any active GCP projects"
395
395
 
396
396
  The \`roles/resourcemanager.projectViewer\` role may not have propagated yet. IAM changes can take up to 60 seconds. Wait and retry.
397
- `.trim()});var A9,_L,UL,PY,j9,E9,KY,VY,$U,OY,WY,A4,LY,NY,vU,qY,kY,j4,HY,FY,_U,bY,gY,UU,SY,BY,DU,DL;var x9=L(()=>{k$();S$();QY();YY();A9=w.enum(["vercel","cloudflare","railway","render","fly_io","heroku","netlify","supabase","planetscale","digital_ocean","inngest","trigger_dev","temporal","mastra","langchain","daytona","e2b","cloudwatch","convex","datadog","sentry","openrouter","posthog","gcl","gcp","otel"]),_L=w.enum(["pending","provisioning","active","error"]),UL=w.object({name:w.string().describe("Field name used as the JSON key in metadata."),type:w.string().describe('Zod type name, e.g. "string", "boolean", "enum".'),required:w.boolean().describe("Whether the field is required."),sensitive:w.boolean().describe("Whether the field contains a secret and will be encrypted."),description:w.string().nullable().describe("Human-readable description of the field.")}),PY=w.object({id:w.string().describe("Data source type identifier."),name:w.string().describe("Human-readable display name."),metadataFields:w.array(UL).describe("Fields required in the metadata object when creating a connection."),setupSkill:w.string().nullable().describe("Markdown setup skill for AI agents. Null when no skill is available.")}),j9=w.object({id:w.string().uuid(),projectId:w.string().uuid(),dataSourceType:A9,displayName:w.string().nullable(),createdAt:w.string().datetime()}),E9=w.object({id:w.string().uuid(),connectionId:w.string().uuid(),displayName:w.string(),config:w.record(w.string(),w.unknown()),status:_L,errorMessage:w.string().nullable(),createdAt:w.string().datetime()}),KY=w.object({}),VY=w.object({types:w.array(PY)}),$U=T({operationId:"dataSources.listTypes",description:"List all supported data source types with their metadata requirements.",backend:"api",route:{method:"GET",path:"/data-sources/types",tags:["Data Sources"]},input:KY,output:VY,pagination:"none",async:"sync"}),OY=w.object({projectId:w.string().uuid().optional().describe("Project to list connections for. Auto-filled from SDK context when omitted."),dataSourceType:A9.optional().describe("Filter connections by data source type.")}),WY=w.object({connections:w.array(j9)}),A4=T({operationId:"dataSources.listConnections",description:"List data source connections within one project.",backend:"api",route:{method:"GET",path:"/data-sources/connections",tags:["Data Sources"]},input:OY,output:WY,pagination:"none",async:"sync"}),LY=w.object({connectionId:w.string().uuid().describe("Connection ID to fetch.")}),NY=w.object({connection:j9}),vU=T({operationId:"dataSources.getConnection",description:"Get one data source connection by ID.",backend:"api",route:{method:"GET",path:"/data-sources/connections/{connectionId}",tags:["Data Sources"]},input:LY,output:NY,pagination:"none",async:"sync"}),qY=w.object({projectId:w.string().uuid().optional().describe("Project to create the connection in. Auto-filled from SDK context when omitted."),dataSourceType:A9.describe("Data source type identifier."),metadata:w.record(w.string(),w.unknown()).describe("Platform-specific credentials. Fields vary by data source type."),displayName:w.string().optional().describe("Optional human-readable name for this connection.")}),kY=w.object({connectionId:w.string().uuid().describe("ID of the created connection."),publicKey:w.string().describe("Auto-generated public API key for this connection. Store this securely — it is only shown once.")}),j4=T({operationId:"dataSources.createConnection",description:"Create a new data source connection. Validates credentials, encrypts sensitive fields, and auto-generates a public API key.",backend:"api",route:{method:"POST",path:"/data-sources/connections",successStatus:201,tags:["Data Sources"]},input:qY,output:kY,pagination:"none",async:"sync"}),HY=w.object({connectionId:w.string().uuid().describe("Connection ID to list streams for.")}),FY=w.object({streams:w.array(E9)}),_U=T({operationId:"dataSources.listStreams",description:"List streams for a data source connection.",backend:"api",route:{method:"GET",path:"/data-sources/connections/{connectionId}/streams",tags:["Data Sources"]},input:HY,output:FY,pagination:"none",async:"sync"}),bY=w.object({connectionId:w.string().uuid().describe("Connection ID to create the stream under."),displayName:w.string().describe("Resource name, e.g. service or app name."),config:w.record(w.string(),w.unknown()).describe("Platform-specific stream configuration.")}),gY=w.object({streamId:w.string().uuid().describe("ID of the created stream.")}),UU=T({operationId:"dataSources.createStream",description:"Create a new stream for a data source connection. Triggers async provisioning.",backend:"api",route:{method:"POST",path:"/data-sources/connections/{connectionId}/streams",successStatus:201,tags:["Data Sources"]},input:bY,output:gY,pagination:"none",async:"sync"}),SY=w.object({streamId:w.string().uuid().describe("Stream ID to fetch.")}),BY=w.object({stream:E9}),DU=T({operationId:"dataSources.getStream",description:"Get one data source stream by ID. Use to poll provisioning status.",backend:"api",route:{method:"GET",path:"/data-sources/streams/{streamId}",tags:["Data Sources"]},input:SY,output:BY,pagination:"none",async:"sync"}),DL={listTypes:$U.contract,listConnections:A4.contract,getConnection:vU.contract,createConnection:j4.contract,listStreams:_U.contract,createStream:UU.contract,getStream:DU.contract}});var IU,ZY,GU,JU,MY,TY,zY,AY,R9,C9,jY,EY,xY,RY,CY,u9,uY,yY,fY,cY,hY,E4,x4,R4,C4,u4,wU,XU,QU,YU,PU,IL,GL;var y9=L(()=>{k$();S$();IU=/^[a-zA-Z0-9\s\-_]+$/,ZY=w.object({id:w.string().uuid(),name:w.string(),expiresAt:w.string().datetime().nullable(),lastUsedAt:w.string().datetime().nullable(),createdAt:w.string().datetime()}),GU=ZY.extend({projectId:w.string().uuid(),dataSourceConnectionId:w.string().uuid().nullable().describe("Linked data source connection ID when this key is scoped to one data source.")}),JU=ZY.extend({projectId:w.string().uuid().nullable()}),MY=w.object({projectId:w.string().uuid().optional().describe("Project to list keys for. Auto-filled from CLI and SDK context when omitted."),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of keys to return per page."),cursor:w.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),TY=w.object({publicKeys:w.array(GU),nextCursor:w.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),zY=w.object({secretKeys:w.array(JU),nextCursor:w.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),AY=w.object({projectId:w.string().uuid().optional().describe("Project containing the key. Auto-filled from CLI and SDK context when omitted."),keyId:w.string().uuid().describe("Key ID to fetch.")}),R9=w.object({publicKey:GU}),C9=w.object({secretKey:JU}),jY=w.object({projectId:w.string().uuid().optional().describe("Project to create the key in. Auto-filled from CLI and SDK context when omitted."),name:w.string().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(IU,"Name can only contain letters, numbers, spaces, hyphens, and underscores").describe("Human-readable name for the key."),expiresAt:w.string().datetime().optional().describe("Optional expiration timestamp for the key.")}),EY=w.object({publicKey:GU.extend({value:w.string()})}),xY=w.object({secretKey:JU.extend({value:w.string()})}),RY=w.object({projectId:w.string().uuid().optional().describe("Project containing the key. Auto-filled from CLI and SDK context when omitted."),keyId:w.string().uuid().describe("Key ID to update."),name:w.string().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(IU,"Name can only contain letters, numbers, spaces, hyphens, and underscores").optional().describe("New human-readable name for the key."),expiresAt:w.string().datetime().nullable().optional().describe("New expiration timestamp for the key, or null to clear it.")}),CY=w.object({params:w.object({keyId:w.string().uuid().describe("Key ID to delete.")}),query:w.object({projectId:w.string().uuid().optional().describe("Project containing the key. Auto-filled from CLI and SDK context when omitted.")})}).transform(({params:$,query:v})=>({...v,...$})),u9=w.object({}),uY=w.object({limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of keys to return per page."),cursor:w.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),yY=w.object({keyId:w.string().uuid().describe("Key ID to fetch.")}),fY=w.object({projectId:w.string().uuid().optional().describe("Project to scope this key to. When set, the key can only access resources within this project. Omit for organization-wide access."),name:w.string().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(IU,"Name can only contain letters, numbers, spaces, hyphens, and underscores").describe("Human-readable name for the key."),expiresAt:w.string().datetime().optional().describe("Optional expiration timestamp for the key.")}),cY=w.object({keyId:w.string().uuid().describe("Key ID to update."),name:w.string().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(IU,"Name can only contain letters, numbers, spaces, hyphens, and underscores").optional().describe("New human-readable name for the key."),expiresAt:w.string().datetime().nullable().optional().describe("New expiration timestamp for the key, or null to clear it.")}),hY=w.object({params:w.object({keyId:w.string().uuid().describe("Key ID to delete.")})}).transform(({params:$})=>({...$})),E4=T({operationId:"publicKeys.list",description:"List public keys within one project.",backend:"api",route:{method:"GET",path:"/public-keys",tags:["Public Keys"]},input:MY,output:TY,pagination:"cursor",async:"sync",examples:[{name:"list-public-keys",input:{projectId:"11111111-1111-4111-8111-111111111111",limit:25},output:{publicKeys:[{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",name:"CLI forwarder",dataSourceConnectionId:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}],nextCursor:null}}]}),x4=T({operationId:"publicKeys.get",description:"Get one public key within one project.",backend:"api",route:{method:"GET",path:"/public-keys/{keyId}",tags:["Public Keys"]},input:AY,output:R9,pagination:"none",async:"sync",examples:[{name:"get-public-key",input:{projectId:"11111111-1111-4111-8111-111111111111",keyId:"22222222-2222-4222-8222-222222222222"},output:{publicKey:{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",name:"CLI forwarder",dataSourceConnectionId:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}}}]}),R4=T({operationId:"publicKeys.create",description:"Create one public key within one project.",backend:"api",route:{method:"POST",path:"/public-keys",successStatus:201,tags:["Public Keys"]},input:jY,output:EY,pagination:"none",async:"sync",examples:[{name:"create-public-key",input:{projectId:"11111111-1111-4111-8111-111111111111",name:"CLI forwarder"},output:{publicKey:{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",name:"CLI forwarder",dataSourceConnectionId:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z",value:"sazabi_public_example"}}}]}),C4=T({operationId:"publicKeys.update",description:"Update one public key within one project.",backend:"api",route:{method:"PATCH",path:"/public-keys/{keyId}",tags:["Public Keys"]},input:RY,output:R9,pagination:"none",async:"sync",examples:[{name:"rename-public-key",input:{projectId:"11111111-1111-4111-8111-111111111111",keyId:"22222222-2222-4222-8222-222222222222",name:"Updated CLI forwarder"},output:{publicKey:{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",name:"Updated CLI forwarder",dataSourceConnectionId:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}}}]}),u4=T({operationId:"publicKeys.delete",description:"Delete one public key within one project.",backend:"api",route:{method:"DELETE",path:"/public-keys/{keyId}",successStatus:204,tags:["Public Keys"],inputStructure:"detailed"},input:CY,output:u9,pagination:"none",async:"sync"}),wU=T({operationId:"secretKeys.list",description:"List secret keys within the organization.",backend:"api",route:{method:"GET",path:"/secret-keys",tags:["Secret Keys"]},input:uY,output:zY,pagination:"cursor",async:"sync",examples:[{name:"list-secret-keys",input:{limit:25},output:{secretKeys:[{id:"33333333-3333-4333-8333-333333333333",projectId:null,name:"CI agent",expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}],nextCursor:null}}]}),XU=T({operationId:"secretKeys.get",description:"Get one secret key within the organization.",backend:"api",route:{method:"GET",path:"/secret-keys/{keyId}",tags:["Secret Keys"]},input:yY,output:C9,pagination:"none",async:"sync",examples:[{name:"get-secret-key",input:{keyId:"33333333-3333-4333-8333-333333333333"},output:{secretKey:{id:"33333333-3333-4333-8333-333333333333",projectId:null,name:"CI agent",expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}}}]}),QU=T({operationId:"secretKeys.create",description:"Create one secret key within the organization.",backend:"api",route:{method:"POST",path:"/secret-keys",successStatus:201,tags:["Secret Keys"]},input:fY,output:xY,pagination:"none",async:"sync",examples:[{name:"create-secret-key",input:{name:"CI agent"},output:{secretKey:{id:"33333333-3333-4333-8333-333333333333",projectId:null,name:"CI agent",expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z",value:"sazabi_secret_example"}}}]}),YU=T({operationId:"secretKeys.update",description:"Update one secret key within the organization.",backend:"api",route:{method:"PATCH",path:"/secret-keys/{keyId}",tags:["Secret Keys"]},input:cY,output:C9,pagination:"none",async:"sync",examples:[{name:"rename-secret-key",input:{keyId:"33333333-3333-4333-8333-333333333333",name:"Updated CI agent"},output:{secretKey:{id:"33333333-3333-4333-8333-333333333333",projectId:null,name:"Updated CI agent",expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}}}]}),PU=T({operationId:"secretKeys.delete",description:"Delete one secret key within the organization.",backend:"api",route:{method:"DELETE",path:"/secret-keys/{keyId}",successStatus:204,tags:["Secret Keys"],inputStructure:"detailed"},input:hY,output:u9,pagination:"none",async:"sync"}),IL={list:E4.contract,get:x4.contract,create:R4.contract,update:C4.contract,delete:u4.contract},GL={list:wU.contract,get:XU.contract,create:QU.contract,update:YU.contract,delete:PU.contract}});var rY,mY,lY,iY,nY,dY,oY,JL,tY,pY,y4,wL;var f9=L(()=>{k$();S$();rY=w.enum(["eq","neq","in","contains","starts_with","gt","gte","lt","lte","between","exists"]).describe("Filter operator: 'eq' (equals), 'neq' (not equals), 'in' (in array), 'contains' (substring), 'starts_with' (prefix), 'gt' (greater than), 'gte' (greater than or equal), 'lt' (less than), 'lte' (less than or equal), 'between' (range), 'exists' (field exists)"),mY=w.enum(["any","all","phrase"]).describe("Search mode: 'any' (match any token), 'all' (match all tokens), 'phrase' (exact phrase match)"),lY=w.object({query:w.string().min(1,"Search query must be at least 1 character").max(500,"Search query must be at most 500 characters").describe("Search query text (1-500 characters)"),fields:w.array(w.string()).optional().describe("Fields to search in (defaults to backend allowlist)"),mode:mY.optional().default("all").describe("Token matching mode")}),iY=w.object({field:w.string().describe("Field name to filter on"),op:rY.describe("Filter operator"),value:w.union([w.string(),w.number(),w.boolean(),w.array(w.union([w.string(),w.number()])),w.object({from:w.string(),to:w.string()})]).describe("Filter value (type depends on operator)")}).superRefine(($,v)=>{if($.op==="in"&&!Array.isArray($.value))v.addIssue({code:w.ZodIssueCode.custom,message:"Value must be an array when op is 'in'",path:["value"]});if($.op==="between"){let U=$.value;if(!(typeof U==="object"&&U!==null&&("from"in U)&&("to"in U)))v.addIssue({code:w.ZodIssueCode.custom,message:"Value must be an object with from/to when op is 'between'",path:["value"]})}if($.op==="exists"&&typeof $.value!=="boolean")v.addIssue({code:w.ZodIssueCode.custom,message:"Value must be boolean when op is 'exists'",path:["value"]})}),nY=w.object({field:w.string().describe("Field name to sort by"),direction:w.enum(["asc","desc"]).default("desc").describe("Sort direction: 'asc' for ascending, 'desc' for descending")}),dY=w.object({limit:w.number().int().min(1,"Limit must be at least 1").max(1000,"Limit must be at most 1000").default(50).describe("Maximum number of rows to return"),cursor:w.string().optional().describe("Opaque cursor from previous response for pagination")}),oY=w.object({projectId:w.string().uuid().optional().describe("Project to query logs for. Auto-filled from CLI and SDK context when omitted."),search:lY.optional().describe("Full-text search configuration"),filters:w.array(iY).optional().describe("Structured filter clauses (ANDed together)"),select:w.array(w.string()).optional().describe("Fields to return (defaults to backend default set)"),sort:nY.optional().describe("Sort configuration (defaults to timestamp desc)"),pagination:dY.optional().describe("Pagination configuration")}),JL=w.object({cursor:w.string().nullable().describe("Cursor for next page (null if no more results)"),hasMore:w.boolean().describe("Whether more results are available")}),tY=w.object({count:w.number().int().nonnegative().describe("Number of log rows returned in this response"),took:w.number().nonnegative().describe("Query execution time in milliseconds")}),pY=w.object({data:w.array(w.record(w.string(),w.any())).describe("Array of log rows with selected fields"),nextCursor:w.string().nullable().describe("Pass as 'cursor' in the next query to fetch the next page. Null when there are no more results."),meta:tY.describe("Query execution metadata")}),y4=T({operationId:"logs.query",description:"Query logs within one project via the platform API proxy.",backend:"api",route:{method:"POST",path:"/logs/query",tags:["Logs"]},input:oY,output:pY,pagination:"cursor",async:"sync"}),wL={query:y4.contract}});var nv,aY,eY,sY,$P,vP,_P,UP,KU,XL;var t6=L(()=>{k$();S$();nv=w.enum(["admin","member"]),aY=w.object({id:w.string().min(1),name:w.string(),slug:w.string(),logo:w.string().nullable().optional(),role:nv}),eY=w.object({id:w.string().min(1),name:w.string().nullable(),email:w.string().email()}),sY=w.object({credentialType:w.literal("user"),user:eY,activeOrganizationId:w.string().min(1).nullable(),organizations:w.array(aY).describe("Organizations the user belongs to, including membership role.")}),$P=w.object({credentialType:w.literal("secret"),organization:w.object({id:w.string().min(1),name:w.string(),slug:w.string(),logo:w.string().nullable().optional()}),keyName:w.string()}),vP=w.object({credentialType:w.literal("partner"),superorganization:w.object({id:w.string().uuid(),name:w.string()})}),_P=w.object({}),UP=w.discriminatedUnion("credentialType",[sY,$P,vP]),KU=T({operationId:"me.get",description:"Return the identity and available context for the current credential.",backend:"api",route:{method:"GET",path:"/me",tags:["Auth"]},input:_P,output:UP,pagination:"none",async:"sync"}),XL=KU.contract});var c9,DP,IP,GP,JP,wP,XP,VU,OU,WU,QL;var h9=L(()=>{k$();S$();t6();c9=w.object({membershipId:w.string().min(1).describe("Organization membership record ID."),userId:w.string().min(1).describe("User ID for the organization member."),name:w.string().nullable().describe("Display name for the member, when available."),email:w.string().email().describe("Email address for the member."),imageUrl:w.string().nullable().describe("Profile image URL for the member, when available."),role:nv.describe("Organization role."),createdAt:w.string().datetime().describe("When the membership was created.")}),DP=w.object({organizationId:w.string().min(1).optional().describe("Organization to list members for. Auto-filled from CLI and SDK context when omitted.")}),IP=w.object({members:w.array(c9).describe("Members visible within the selected organization.")}),GP=w.object({organizationId:w.string().min(1).optional().describe("Organization containing the member. Auto-filled from CLI and SDK context when omitted."),userId:w.string().min(1).describe("User ID of the member to update."),role:nv.describe("Role to assign.")}),JP=w.object({member:c9.describe("Updated organization member.")}),wP=w.object({params:w.object({userId:w.string().min(1).describe("User ID of the member to remove.")}),query:w.object({organizationId:w.string().min(1).optional().describe("Organization containing the member. Auto-filled from CLI and SDK context when omitted.")})}).transform(({params:$,query:v})=>({...v,...$})),XP=w.object({removedUserId:w.string().min(1).describe("User ID removed from the organization.")}),VU=T({operationId:"members.list",description:"List members in an organization.",backend:"api",route:{method:"GET",path:"/members",tags:["Members"]},input:DP,output:IP,pagination:"none",async:"sync",examples:[{name:"organization-members",input:{organizationId:"organization-123"},output:{members:[{membershipId:"membership-123",userId:"user-123",name:"Alex Admin",email:"alex@example.com",imageUrl:null,role:"admin",createdAt:"2026-01-01T00:00:00.000Z"}]}}]}),OU=T({operationId:"members.updateRole",description:"Update a member's organization role.",backend:"api",route:{method:"PATCH",path:"/members/{userId}/role",tags:["Members"]},input:GP,output:JP,pagination:"none",async:"sync",examples:[{name:"promote-member",input:{organizationId:"organization-123",userId:"user-456",role:"admin"},output:{member:{membershipId:"membership-456",userId:"user-456",name:"Mina Member",email:"mina@example.com",imageUrl:null,role:"admin",createdAt:"2026-01-01T00:00:00.000Z"}}}]}),WU=T({operationId:"members.remove",description:"Remove a member from an organization.",backend:"api",route:{method:"DELETE",path:"/members/{userId}",tags:["Members"],inputStructure:"detailed"},input:wP,output:XP,pagination:"none",async:"sync"}),QL={list:VU.contract,updateRole:OU.contract,remove:WU.contract}});var QP,r9,YP,PP,KP,VP,OP,f4,WP,LU,NU,qU,YL;var p6=L(()=>{k$();S$();QP=w.enum(["processing","completed","aborted","error"]),r9=w.object({id:w.string().uuid(),threadId:w.string().uuid(),userMessageId:w.string().uuid().nullable(),assistantMessageId:w.string().uuid().nullable(),parentRunId:w.string().uuid().nullable(),workflowRunId:w.string().nullable(),status:QP,source:w.enum(["web","api","mcp","slack","agent","cli"]),createdAt:w.string().datetime(),updatedAt:w.string().datetime(),completedAt:w.string().datetime().nullable()}),YP=w.object({projectId:w.string().uuid().optional().describe("Project ID to list runs for. Auto-filled from CLI and SDK context when omitted."),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of runs to return per page."),cursor:w.string().datetime().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),PP=w.object({runs:w.array(r9),nextCursor:w.string().datetime().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),KP=w.object({threadId:w.string().uuid().describe("Thread ID to list runs for."),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of runs to return per page."),cursor:w.string().datetime().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),VP=w.object({runs:w.array(r9),nextCursor:w.string().datetime().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),OP=w.object({runId:w.string().uuid().describe("Run ID returned by a deferred operation.")}),f4=w.object({completed:w.boolean().describe("Whether the run has reached a terminal status."),threadId:w.string().uuid().describe("Thread ID associated with the run."),runId:w.string().uuid().describe("Run ID for subsequent polling."),status:QP.describe("Current run lifecycle status."),response:w.string().nullable().describe("Assistant response text when the run has completed.")}),WP=f4.describe("Current run state and, when complete, the assistant response."),LU=T({operationId:"runs.list",description:"List deferred runs within one project.",backend:"api",route:{method:"GET",path:"/runs",tags:["Runs"]},input:YP,output:PP,pagination:"cursor",async:"sync"}),NU=T({operationId:"runs.listForThread",description:"List deferred runs for one thread.",backend:"api",route:{method:"GET",path:"/threads/{threadId}/runs",tags:["Runs"]},input:KP,output:VP,pagination:"cursor",async:"sync"}),qU=T({operationId:"runs.get",description:"Get the current result for a deferred run by run ID.",backend:"api",route:{method:"GET",path:"/runs/{runId}",tags:["Runs"]},input:OP,output:WP,pagination:"none",async:"sync",examples:[{name:"processing-run",input:{runId:"33333333-3333-4333-8333-333333333333"},output:{completed:!1,threadId:"22222222-2222-4222-8222-222222222222",runId:"33333333-3333-4333-8333-333333333333",status:"processing",response:null}}]}),YL={list:LU.contract,listForThread:NU.contract,get:qU.contract}});var kU,PL,KL,VL,OL,WL,LL,NL,qL,HU,LP,NP,qP,kP,HP,FP,bP,gP,SP,BP,FU,bU,gU,SU,BU,kL;var ZU=L(()=>{k$();S$();p6();kU=w.object({id:w.string().uuid(),projectId:w.string().uuid(),title:w.string().nullable(),status:w.enum(["regular","archived"]),createdAt:w.string().datetime(),updatedAt:w.string().datetime()}),PL=w.object({type:w.literal("message"),message:w.string()}),KL=w.object({type:w.literal("reasoning"),reasoning:w.string(),status:w.enum(["in_progress","complete"]).optional()}),VL=w.object({type:w.literal("tool_call"),name:w.string(),params:w.any().optional(),result:w.any().optional(),status:w.enum(["in_progress","success","error","unknown"]).optional(),toolCallId:w.string().optional(),durationMs:w.number().nonnegative().optional()}),OL=w.object({type:w.literal("artifact"),name:w.enum(["timeseries","table","log_detail","integration_required","alert_card"]),data:w.any(),toolCallId:w.string().optional()}),WL=w.object({type:w.literal("fork"),sourceThreadId:w.string(),sourceMessageId:w.string(),sourceThreadTitle:w.string().nullable()}),LL=w.object({type:w.literal("summary"),summary:w.string()}),NL=w.object({type:w.literal("slack_context"),channelId:w.string(),isTruncated:w.boolean().optional(),messages:w.array(w.object({timestamp:w.string(),slackUserId:w.string().optional(),displayName:w.string(),text:w.string(),isBot:w.boolean(),files:w.array(w.object({name:w.string(),mimetype:w.string(),size:w.number().optional(),attachmentId:w.string().uuid().optional(),ingestionStatus:w.enum(["attached","unsupported","oversized","skipped","unavailable"]).optional()})).optional()}))}),qL=w.union([PL,KL,VL,OL,WL,LL,NL]),HU=w.object({id:w.string().uuid(),role:w.enum(["user","assistant"]),content:w.array(qL),createdAt:w.string().datetime()}),LP=w.object({projectId:w.string().uuid().optional().describe("Project to list threads for. Auto-filled from CLI and SDK context when omitted."),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of threads to return per page."),cursor:w.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page."),status:w.enum(["regular","archived"]).optional().describe("Filter by thread status. 'regular' returns active threads, 'archived' returns archived threads.")}),NP=w.object({threads:w.array(kU).describe("The page of threads matching the query."),nextCursor:w.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),qP=w.object({threadId:w.string().uuid().describe("Thread ID returned by threads.list or threads.create.")}),kP=w.object({thread:kU.describe("The requested thread."),messages:w.array(HU).describe("Messages currently stored on the thread in chronological order.")}),HP=w.object({projectId:w.string().uuid().optional().describe("Project to create the thread in. Auto-filled from CLI and SDK context when omitted."),message:w.string().min(1,"Message cannot be empty").max(1e4,"Message cannot exceed 10000 characters").describe("Initial user message that starts the thread."),wait:w.boolean().default(!0).describe("Whether the server should wait for the agent run before responding."),timeoutSeconds:w.coerce.number().int().min(1).max(20).default(20).describe("Maximum seconds to wait when wait is true before handing off to polling.")}),FP=f4.describe("Deferred run result for creating a thread."),bP=w.object({threadId:w.string().uuid().describe("Thread ID whose current processing status should be returned.")}),gP=w.object({status:w.enum(["idle","processing"]),lastRunStatus:w.enum(["error"]).nullable()}),SP=w.object({threadId:w.string().uuid().describe("Thread ID of the thread to update."),status:w.enum(["regular","archived"]).describe("New status for the thread. 'archived' hides the thread from the sidebar.")}),BP=w.object({thread:kU.describe("The updated thread.")}),FU=T({operationId:"threads.list",description:"List threads in a project, optionally filtered by status.",backend:"api",route:{method:"GET",path:"/threads",tags:["Threads"]},input:LP,output:NP,pagination:"cursor",async:"sync",examples:[{name:"active-threads",input:{projectId:"11111111-1111-4111-8111-111111111111",status:"regular",limit:10},output:{threads:[{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",title:"API returning 500s",status:"regular",createdAt:"2026-01-01T00:00:00.000Z",updatedAt:"2026-01-01T00:05:00.000Z"}],nextCursor:null}}]}),bU=T({operationId:"threads.get",description:"Get a thread and its messages.",backend:"api",route:{method:"GET",path:"/threads/{threadId}",tags:["Threads"]},input:qP,output:kP,pagination:"none",async:"sync"}),gU=T({operationId:"threads.getStatus",description:"Get the current processing status for a thread.",backend:"api",route:{method:"GET",path:"/threads/{threadId}/status",tags:["Threads"]},input:bP,output:gP,pagination:"none",async:"sync",examples:[{name:"processing-thread",input:{threadId:"22222222-2222-4222-8222-222222222222"},output:{status:"processing",lastRunStatus:null}}]}),SU=T({operationId:"threads.create",description:"Create a thread with an initial message and optionally wait for the agent response.",backend:"api",route:{method:"POST",path:"/threads",tags:["Threads"],successStatus:201},input:HP,output:FP,pagination:"none",async:"deferred",examples:[{name:"async-handoff",input:{projectId:"11111111-1111-4111-8111-111111111111",message:"Investigate elevated 500s in production.",wait:!1,timeoutSeconds:20},output:{completed:!1,threadId:"22222222-2222-4222-8222-222222222222",runId:"33333333-3333-4333-8333-333333333333",status:"processing",response:null}}]}),BU=T({operationId:"threads.update",description:"Update a thread's status.",backend:"api",route:{method:"PATCH",path:"/threads/{threadId}",tags:["Threads"]},input:SP,output:BP,pagination:"none",async:"sync",examples:[{name:"archive-thread",input:{threadId:"22222222-2222-4222-8222-222222222222",status:"archived"},output:{thread:{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",title:"API returning 500s",status:"archived",createdAt:"2026-01-01T00:00:00.000Z",updatedAt:"2026-01-01T00:10:00.000Z"}}}]}),kL={list:FU.contract,get:bU.contract,getStatus:gU.contract,create:SU.contract,update:BU.contract}});var ZP,MP,TP,zP,m9,l9;var i9=L(()=>{k$();S$();p6();ZU();ZP=w.object({threadId:w.string().uuid().describe("Thread ID to list messages for."),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of messages to return per page."),cursor:w.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),MP=w.object({messages:w.array(HU),nextCursor:w.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),TP=w.object({threadId:w.string().uuid().describe("Thread ID to append the message to."),message:w.string().min(1,"Message cannot be empty").max(1e4,"Message cannot exceed 10000 characters"),wait:w.boolean().default(!0).describe("Whether the server should wait for the appended message run before responding."),timeoutSeconds:w.coerce.number().int().min(1).max(20).default(20).describe("Maximum seconds to wait when wait is true before handing off to polling.")}),zP=f4.describe("Deferred run result for appending a message to an existing thread."),m9=T({operationId:"messages.list",description:"List messages in a thread with cursor pagination.",backend:"api",route:{method:"GET",path:"/threads/{threadId}/messages",tags:["Messages"]},input:ZP,output:MP,pagination:"cursor",async:"sync",examples:[{name:"thread-messages",input:{threadId:"22222222-2222-4222-8222-222222222222",limit:2},output:{messages:[{id:"33333333-3333-4333-8333-333333333333",role:"user",content:[{type:"message",message:"What changed in the intake pipeline?"}],createdAt:"2026-01-01T00:00:00.000Z"}],nextCursor:null}}]}),l9=T({operationId:"messages.append",description:"Append a user message to an existing thread and trigger a deferred run.",backend:"api",route:{method:"POST",path:"/threads/{threadId}/messages",successStatus:201,tags:["Messages"]},input:TP,output:zP,pagination:"none",async:"deferred",examples:[{name:"append-processing",input:{threadId:"22222222-2222-4222-8222-222222222222",message:"Follow up on the intake backlog.",wait:!1,timeoutSeconds:20},output:{completed:!1,threadId:"22222222-2222-4222-8222-222222222222",runId:"33333333-3333-4333-8333-333333333333",status:"processing",response:null}}]})});var MU,AP,jP,EP,xP,RP,CP,uP,TU,zU,AU,HL;var n9=L(()=>{k$();S$();t6();MU=w.object({id:w.string().min(1),name:w.string(),slug:w.string(),logo:w.string().nullable().optional()}),AP=MU.extend({role:nv.optional()}),jP=w.object({}),EP=w.object({organizations:w.array(AP).describe("Organizations available to the current credential.")}),xP=w.object({organizationId:w.string().min(1).describe("Organization ID to fetch.")}),RP=w.object({organization:MU}),CP=w.object({organizationId:w.string().min(1).describe("Organization ID to update. SDK and CLI callers can auto-fill this before dispatch."),name:w.string().trim().min(1).max(100).describe("New organization name.")}),uP=w.object({organization:MU.describe("Updated organization.")}),TU=T({operationId:"organizations.list",description:"List organizations available to the current credential.",backend:"api",route:{method:"GET",path:"/organizations",tags:["Organizations"]},input:jP,output:EP,pagination:"none",async:"sync"}),zU=T({operationId:"organizations.get",description:"Get one organization by ID.",backend:"api",route:{method:"GET",path:"/organizations/{organizationId}",tags:["Organizations"]},input:xP,output:RP,pagination:"none",async:"sync"}),AU=T({operationId:"organizations.update",description:"Update one organization.",backend:"api",route:{method:"PATCH",path:"/organizations/{organizationId}",tags:["Organizations"]},input:CP,output:uP,pagination:"none",async:"sync",examples:[{name:"rename-organization",input:{organizationId:"organization-123",name:"Observed Platform"},output:{organization:{id:"organization-123",name:"Observed Platform",slug:"acme",logo:null}}}]}),HL={list:TU.contract,get:zU.contract,update:AU.contract}});var jU,d9,yP,fP,cP,hP,EU,xU,FL;var o9=L(()=>{k$();S$();jU=w.enum(["us-east-1","us-east-2","us-west-1","us-west-2","eu-central-1","eu-central-2","eu-north-1","eu-south-1","eu-south-2","eu-west-1","eu-west-2","eu-west-3"]),d9=w.object({id:w.string().uuid(),organizationId:w.string().min(1),name:w.string(),region:jU}),yP=w.object({organizationId:w.string().min(1).optional().describe("Organization to list projects for. Auto-filled from CLI and SDK context when omitted.")}),fP=w.object({projects:w.array(d9).describe("Projects visible within the selected organization.")}),cP=w.object({projectId:w.string().uuid().describe("Project ID to fetch.")}),hP=w.object({project:d9}),EU=T({operationId:"projects.list",description:"List projects in an organization.",backend:"api",route:{method:"GET",path:"/projects",tags:["Projects"]},input:yP,output:fP,pagination:"none",async:"sync"}),xU=T({operationId:"projects.get",description:"Get one project by ID.",backend:"api",route:{method:"GET",path:"/projects/{projectId}",tags:["Projects"]},input:cP,output:hP,pagination:"none",async:"sync"}),FL={list:EU.contract,get:xU.contract}});var t9,rP,mP,lP,iP,c4,h4,bL;var p9=L(()=>{k$();S$();t9=w.object({projectId:w.string().uuid().optional().describe("Project to search within. Auto-filled from CLI and SDK context when omitted."),query:w.string().trim().min(1,"Query must be at least 1 character").max(500,"Query must be at most 500 characters"),limit:w.coerce.number().min(1).max(100).default(20).describe("Maximum number of search results to return."),page:w.coerce.number().min(1).default(1).describe("One-based page number.")}),rP=t9.extend({status:w.enum(["regular","archived"]).optional().describe("Optional thread status filter.")}),mP=t9.extend({threadId:w.string().uuid().optional().describe("Optional thread restriction for message search."),role:w.enum(["user","assistant"]).optional().describe("Optional message role filter.")}),lP=w.object({threads:w.array(w.object({id:w.string().uuid(),projectId:w.string().uuid().optional(),title:w.string(),status:w.enum(["regular","archived"]),labels:w.array(w.string()),createdAt:w.string().datetime(),updatedAt:w.string().datetime(),highlights:w.array(w.string()),score:w.number().optional()})),pagination:w.object({page:w.number(),limit:w.number(),totalResults:w.number(),totalPages:w.number()}).describe("Page-based pagination metadata for the current search result.")}),iP=w.object({messages:w.array(w.object({id:w.string().uuid(),threadId:w.string().uuid(),threadTitle:w.string(),role:w.enum(["user","assistant"]),content:w.string(),createdAt:w.string().datetime(),updatedAt:w.string().datetime(),highlights:w.array(w.string()),score:w.number().optional()})),pagination:w.object({page:w.number(),limit:w.number(),totalResults:w.number(),totalPages:w.number()}).describe("Page-based pagination metadata for the current search result.")}),c4=T({operationId:"search.threads",description:"Search threads within one project.",backend:"api",route:{method:"GET",path:"/search/threads",tags:["Search"]},input:rP,output:lP,pagination:"page",async:"sync",examples:[{name:"search-open-incidents",input:{projectId:"11111111-1111-4111-8111-111111111111",query:"payment timeout",status:"regular",limit:10,page:1},output:{threads:[{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",title:"Payment timeout in us-west-2",status:"regular",labels:["payments","timeout"],createdAt:"2026-01-01T00:00:00.000Z",updatedAt:"2026-01-02T00:00:00.000Z",highlights:["payment timeout"],score:123.45}],pagination:{page:1,limit:10,totalResults:1,totalPages:1}}}]}),h4=T({operationId:"search.messages",description:"Search messages within one project.",backend:"api",route:{method:"GET",path:"/search/messages",tags:["Search"]},input:mP,output:iP,pagination:"page",async:"sync",examples:[{name:"search-assistant-messages",input:{projectId:"11111111-1111-4111-8111-111111111111",query:"rollback",role:"assistant",limit:10,page:1},output:{messages:[{id:"33333333-3333-4333-8333-333333333333",threadId:"22222222-2222-4222-8222-222222222222",threadTitle:"Deployment rollback guidance",role:"assistant",content:"Rollback the ingestion deployment and confirm queue depth.",createdAt:"2026-01-02T00:00:00.000Z",updatedAt:"2026-01-02T00:00:00.000Z",highlights:["Rollback the ingestion deployment"],score:98.76}],pagination:{page:1,limit:10,totalResults:1,totalPages:1}}}]}),bL={threads:c4.contract,messages:h4.contract}});var a9;var nP=L(()=>{x9();y9();f9();t6();h9();i9();n9();o9();p6();p9();ZU();a9={me:KU.contract,logs:{query:y4.contract},dataSources:{listTypes:$U.contract,listConnections:A4.contract,getConnection:vU.contract,createConnection:j4.contract,listStreams:_U.contract,createStream:UU.contract,getStream:DU.contract},organizations:{list:TU.contract,get:zU.contract,update:AU.contract},members:{list:VU.contract,updateRole:OU.contract,remove:WU.contract},publicKeys:{list:E4.contract,get:x4.contract,create:R4.contract,update:C4.contract,delete:u4.contract},secretKeys:{list:wU.contract,get:XU.contract,create:QU.contract,update:YU.contract,delete:PU.contract},projects:{list:EU.contract,get:xU.contract},search:{threads:c4.contract,messages:h4.contract},messages:{list:m9.contract,append:l9.contract},threads:{list:FU.contract,get:bU.contract,getStatus:gU.contract,create:SU.contract,update:BU.contract},runs:{list:LU.contract,listForThread:NU.contract,get:qU.contract}}});var r4,e9,dP,oP,a6,tP,pP,aP,eP,sP,$K,vK,_K,UK,DK,e6,IK,GK,JK,wK,XK,QK,YK,PK,KK,VK,s9,OK,WK,LK,NK,qK,kK,$w,HK,FK,bK,gK,SK,BK,ZK,MK,TK,zK,AK,jK,EK,xK,RK,CK,uK,yK,fK,cK,hK,rK,mK,gL;var lK=L(()=>{k$();S$();r4=/^[a-zA-Z0-9\s\-_]+$/,e9=w.enum(["us-west-2","us-east-1","eu-central-1"]),dP=w.object({id:w.string().uuid(),name:w.string(),createdAt:w.string().datetime()}),oP=w.object({superorganization:dP}),a6=w.object({id:w.string(),name:w.string(),createdAt:w.string().datetime()}),tP=w.object({limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of organizations to return per page."),cursor:w.string().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),pP=w.object({organizations:w.array(a6),nextCursor:w.string().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),aP=w.object({organizationId:w.string()}),eP=w.object({organization:a6}),sP=w.object({name:w.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(r4,"Name can only contain letters, numbers, spaces, hyphens, and underscores")}),$K=w.object({organization:a6}),vK=w.object({organizationId:w.string(),name:w.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(r4,"Name can only contain letters, numbers, spaces, hyphens, and underscores").optional()}),_K=w.object({organization:a6}),UK=w.object({params:w.object({organizationId:w.string()}),query:w.object({})}).transform(({params:$})=>$),DK=w.object({}),e6=w.object({id:w.string().uuid(),organizationId:w.string(),name:w.string(),region:e9,createdAt:w.string().datetime()}),IK=w.object({organizationId:w.string(),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of projects to return per page."),cursor:w.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),GK=w.object({projects:w.array(e6),nextCursor:w.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),JK=w.object({organizationId:w.string(),projectId:w.string().uuid().describe("Project ID to fetch.")}),wK=w.object({project:e6}),XK=w.object({organizationId:w.string(),name:w.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(r4,"Name can only contain letters, numbers, spaces, hyphens, and underscores"),region:e9.optional().default("us-west-2").describe("AWS region where the new project should be created.")}),QK=w.object({project:e6}),YK=w.object({organizationId:w.string(),projectId:w.string().uuid().describe("Project ID to update."),name:w.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(r4,"Name can only contain letters, numbers, spaces, hyphens, and underscores").optional()}),PK=w.object({project:e6}),KK=w.object({params:w.object({organizationId:w.string(),projectId:w.string().uuid().describe("Project ID to delete.")}),query:w.object({})}).transform(({params:$})=>$),VK=w.object({}),s9=w.object({id:w.string().uuid(),projectId:w.string().uuid().nullable(),name:w.string(),expiresAt:w.string().datetime().nullable(),lastUsedAt:w.string().datetime().nullable(),createdAt:w.string().datetime()}),OK=w.object({organizationId:w.string(),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of secret keys to return per page."),cursor:w.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),WK=w.object({secretKeys:w.array(s9),nextCursor:w.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),LK=w.object({organizationId:w.string(),name:w.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(r4,"Name can only contain letters, numbers, spaces, hyphens, and underscores"),expiresAt:w.string().datetime().optional(),projectId:w.string().uuid().optional().describe("Project to scope this key to. When set, the key can only access resources within this project.")}),NK=w.object({secretKey:s9.extend({value:w.string()})}),qK=w.object({params:w.object({organizationId:w.string(),keyId:w.string().uuid().describe("Secret key ID to delete.")}),query:w.object({})}).transform(({params:$})=>$),kK=w.object({}),$w=w.object({id:w.string().uuid(),projectId:w.string().uuid(),name:w.string(),expiresAt:w.string().datetime().nullable(),lastUsedAt:w.string().datetime().nullable(),createdAt:w.string().datetime()}),HK=w.object({organizationId:w.string(),projectId:w.string().uuid().describe("Project ID to list public keys for."),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of public keys to return per page."),cursor:w.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),FK=w.object({publicKeys:w.array($w),nextCursor:w.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),bK=w.object({organizationId:w.string(),projectId:w.string().uuid().describe("Project ID where the key should be created."),name:w.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(r4,"Name can only contain letters, numbers, spaces, hyphens, and underscores"),expiresAt:w.string().datetime().optional()}),gK=w.object({publicKey:$w.extend({value:w.string()})}),SK=w.object({params:w.object({organizationId:w.string(),projectId:w.string().uuid().describe("Project ID that owns the key."),keyId:w.string().uuid().describe("Public key ID to delete.")}),query:w.object({})}).transform(({params:$})=>$),BK=w.object({}),ZK=T({operationId:"partner.superorganization.get",description:"Get the authenticated partner superorganization.",backend:"partner",route:{method:"GET",path:"/superorganization",tags:["Partner - Superorganization"]},input:w.object({}),output:oP,pagination:"none",async:"sync"}),MK=T({operationId:"partner.organizations.list",description:"List organizations under the authenticated superorganization.",backend:"partner",route:{method:"GET",path:"/organizations",tags:["Partner - Organizations"]},input:tP,output:pP,pagination:"cursor",async:"sync"}),TK=T({operationId:"partner.organizations.get",description:"Get one organization under the authenticated superorganization.",backend:"partner",route:{method:"GET",path:"/organizations/{organizationId}",tags:["Partner - Organizations"]},input:aP,output:eP,pagination:"none",async:"sync"}),zK=T({operationId:"partner.organizations.create",description:"Create one organization under the authenticated superorganization.",backend:"partner",route:{method:"POST",path:"/organizations",tags:["Partner - Organizations"],successStatus:201},input:sP,output:$K,pagination:"none",async:"sync"}),AK=T({operationId:"partner.organizations.update",description:"Update one organization under the authenticated superorganization.",backend:"partner",route:{method:"PATCH",path:"/organizations/{organizationId}",tags:["Partner - Organizations"]},input:vK,output:_K,pagination:"none",async:"sync"}),jK=T({operationId:"partner.organizations.delete",description:"Delete one organization under the authenticated superorganization.",backend:"partner",route:{method:"DELETE",path:"/organizations/{organizationId}",tags:["Partner - Organizations"],successStatus:204,inputStructure:"detailed"},input:UK,output:DK,pagination:"none",async:"sync"}),EK=T({operationId:"partner.projects.list",description:"List projects under one partner-managed organization.",backend:"partner",route:{method:"GET",path:"/organizations/{organizationId}/projects",tags:["Partner - Projects"]},input:IK,output:GK,pagination:"cursor",async:"sync"}),xK=T({operationId:"partner.projects.get",description:"Get one project under one partner-managed organization.",backend:"partner",route:{method:"GET",path:"/organizations/{organizationId}/projects/{projectId}",tags:["Partner - Projects"]},input:JK,output:wK,pagination:"none",async:"sync"}),RK=T({operationId:"partner.projects.create",description:"Create one project under one partner-managed organization.",backend:"partner",route:{method:"POST",path:"/organizations/{organizationId}/projects",tags:["Partner - Projects"],successStatus:201},input:XK,output:QK,pagination:"none",async:"sync"}),CK=T({operationId:"partner.projects.update",description:"Update one project under one partner-managed organization.",backend:"partner",route:{method:"PATCH",path:"/organizations/{organizationId}/projects/{projectId}",tags:["Partner - Projects"]},input:YK,output:PK,pagination:"none",async:"sync"}),uK=T({operationId:"partner.projects.delete",description:"Delete one project under one partner-managed organization.",backend:"partner",route:{method:"DELETE",path:"/organizations/{organizationId}/projects/{projectId}",tags:["Partner - Projects"],successStatus:204,inputStructure:"detailed"},input:KK,output:VK,pagination:"none",async:"sync"}),yK=T({operationId:"partner.secretKeys.list",description:"List secret keys under one partner-managed organization.",backend:"partner",route:{method:"GET",path:"/organizations/{organizationId}/secret-keys",tags:["Partner - Secret Keys"]},input:OK,output:WK,pagination:"cursor",async:"sync"}),fK=T({operationId:"partner.secretKeys.create",description:"Create one secret key under one partner-managed organization.",backend:"partner",route:{method:"POST",path:"/organizations/{organizationId}/secret-keys",tags:["Partner - Secret Keys"],successStatus:201},input:LK,output:NK,pagination:"none",async:"sync"}),cK=T({operationId:"partner.secretKeys.delete",description:"Delete one secret key under one partner-managed organization.",backend:"partner",route:{method:"DELETE",path:"/organizations/{organizationId}/secret-keys/{keyId}",tags:["Partner - Secret Keys"],successStatus:204,inputStructure:"detailed"},input:qK,output:kK,pagination:"none",async:"sync"}),hK=T({operationId:"partner.publicKeys.list",description:"List public keys under one partner-managed project.",backend:"partner",route:{method:"GET",path:"/organizations/{organizationId}/projects/{projectId}/public-keys",tags:["Partner - Public Keys"]},input:HK,output:FK,pagination:"cursor",async:"sync"}),rK=T({operationId:"partner.publicKeys.create",description:"Create one public key under one partner-managed project.",backend:"partner",route:{method:"POST",path:"/organizations/{organizationId}/projects/{projectId}/public-keys",tags:["Partner - Public Keys"],successStatus:201},input:bK,output:gK,pagination:"none",async:"sync"}),mK=T({operationId:"partner.publicKeys.delete",description:"Delete one public key under one partner-managed project.",backend:"partner",route:{method:"DELETE",path:"/organizations/{organizationId}/projects/{projectId}/public-keys/{keyId}",tags:["Partner - Public Keys"],successStatus:204,inputStructure:"detailed"},input:SK,output:BK,pagination:"none",async:"sync"}),gL={superorganization:{get:ZK.contract},organizations:{list:MK.contract,get:TK.contract,create:zK.contract,update:AK.contract,delete:jK.contract},projects:{list:EK.contract,get:xK.contract,create:RK.contract,update:CK.contract,delete:uK.contract},keys:{secretKeys:{list:yK.contract,create:fK.contract,delete:cK.contract},publicKeys:{list:hK.contract,create:rK.contract,delete:mK.contract}}}});var vw=L(()=>{nP();x9();S$();y9();f9();t6();h9();i9();n9();lK();o9();p6();p9();ZU()});var SL,yS,BL,RU=($)=>{return BL.includes($)};var _w=L(()=>{SL={"eu-central-1":"EU Central (Frankfurt)"},yS={"us-west-2":"US West","us-east-1":"US East","eu-central-1":SL["eu-central-1"]},BL=["us-west-2","us-east-1","eu-central-1"]});var Uw,Dw,Iw,iK;var nK=L(()=>{k$();Uw=w.object({severities:w.array(w.string()).optional().describe("Limit results to the listed severities."),services:w.array(w.string()).optional().describe("Limit results to the listed service names."),environments:w.array(w.string()).optional().describe("Limit results to the listed deployment environments."),searchTerm:w.string().optional().describe("Case-insensitive substring match against the log body."),traceId:w.string().optional().describe("Limit results to one trace ID.")}),Dw=w.object({service:w.string(),namespace:w.string(),environment:w.string(),host:w.string(),container:w.string(),pod:w.string()}),Iw=w.object({id:w.string(),timestamp:w.string().datetime(),severity:w.string(),body:w.string(),service:w.string(),traceId:w.string(),spanId:w.string(),attributes:w.record(w.string(),w.string()),resource:Dw}),iK=w.object({type:w.literal("logs"),timestamp:w.string().datetime(),data:w.array(Iw)})});var ZL="https://{region}.intake.sazabi.com",ML="wss://{region}.tail.sazabi.com",TL=3,oK=500,tK="sazabi.public_key",zL=($)=>{return $.startsWith("[")&&$.endsWith("]")?$.slice(1,-1):$},pK=($)=>{let v=zL($);return v==="localhost"||v==="127.0.0.1"||v==="::1"},AL,jL,EL,aK=($)=>{let v=new Map;return{tail:async(U)=>{let D=await hL($.credentialProvider,U.projectId,"logs.tail"),_=await rL($,v,D,U.region,"logs.tail"),I=xL({projectId:D,region:_,filters:U.filters,tailBaseUrl:$.tailBaseUrl}),G=await $.credentialProvider.getToken(),J=$.webSocket??globalThis.WebSocket;if(!J)throw Error("WebSocket transport is not available in this runtime.");return iL({token:G,url:I,signal:U.signal,webSocket:J})},forward:async(U)=>{let D=await mL($,v,U.projectId??await $.credentialProvider.getProjectId?.(),U.region,"logs.forward"),_=uL(D,$.intakeBaseUrl),I=$.fetch??globalThis.fetch,G=fL(U.logs,U.publicKey),J=tL(G);return await oL(I,_,G),{forwardedCount:J,failedCount:0}}}},xL=($)=>{let v=($.tailBaseUrl??ML).replace("{region}",$.region),U=RL(v)??new URL(v);U.searchParams.set("projectId",$.projectId);let D=CL($.filters);if(D)U.searchParams.set("filters",D);return U.toString()},RL=($)=>{let v=(()=>{try{return new URL($)}catch{return null}})();if(!v)return;if(!pK(v.hostname))return;return v.protocol="ws:",v.pathname="/tail",v},CL=($)=>{if(!$)return;let v=Object.entries($).filter(([,U])=>U!==void 0&&(!Array.isArray(U)||U.length>0)&&U!=="");if(v.length===0)return;return JSON.stringify(Object.fromEntries(v))},uL=($,v)=>{let U=(v??ZL).replace("{region}",$),D=U.endsWith("/")?U.slice(0,-1):U,_=yL(D);if(_)return _;let I=D.match(/^https:\/\/([a-z0-9-]+)\.intake\.([a-z0-9.]+)$/);return`${I?`https://otlp.${I[1]}.intake.${I[2]}`:D}/v1/logs`},yL=($)=>{let v=(()=>{try{return new URL($)}catch{return null}})();if(!v)return;if(!pK(v.hostname))return;return v.pathname="/adapters/otlp",v.toString()},fL=($,v)=>{let U=$.resourceLogs;if(!U||U.length===0)return{...$,resourceLogs:[{resource:{attributes:[eK(v)]},scopeLogs:[]}]};return{...$,resourceLogs:U.map((D)=>({...D,resource:{...D.resource,attributes:cL(D.resource?.attributes,v)}}))}},cL=($,v)=>{return[...($??[]).filter((D)=>D?.key!==tK),eK(v)]},eK=($)=>({key:tK,value:{stringValue:$}}),hL=async($,v,U)=>{let D=v??await $.getProjectId?.();if(D)return D;throw $7(U,"Project ID is required",["projectId"])},rL=async($,v,U,D,_)=>{let I=D??await sK($,v,U);return lL(I,_)},mL=async($,v,U,D,_)=>{if(D)return D;if(!U)throw $7(_,"Project ID is required",["projectId"]);return sK($,v,U)},sK=async($,v,U)=>{let D=v.get(U);if(D)return D;let _=$.raw.projects.get({projectId:U}).then((I)=>I.project.region);v.set(U,_);try{return await _}catch(I){throw v.delete(U),I}},lL=($,v)=>{if(RU($))return $;throw new D$("BAD_REQUEST",{message:`Log tail is not supported for project region ${$}.`,data:{operationId:v,missingContext:[]}})},iL=async($)=>{let v=[],U=[],D=!1,_=!1,I,G=0,J,X=(O)=>{if(D)return;D=!0,I=O;while(U.length>0){let S=U.shift();if(S)S({value:void 0,done:!0})}},Q=(O)=>{let S=U.shift();if(S){S({value:O,done:!1});return}v.push(O)},Y=()=>{if(J&&J.readyState<J.CLOSING)J.close(1000,"Client closed stream")},P=async()=>{await new Promise((O,S)=>{let B=!1,h;try{h=new $.webSocket($.url,[$.token])}catch(p){S(p instanceof Error?p:Error("Failed to open WebSocket connection."));return}J=h,h.onopen=()=>{if(G=0,!B)B=!0,O()},h.onmessage=(p)=>{let X$=nL(p.data);for(let $$ of X$)Q($$)},h.onerror=()=>{if(!B)B=!0,S(Error("WebSocket connection failed. Check the close event for details."))},h.onclose=(p)=>{if(!B){B=!0,S(dK(p.code,p.reason));return}if(_||D){X();return}if(dL(p.code)&&G<TL){G+=1,globalThis.setTimeout(()=>{P().catch((X$)=>{X(X$ instanceof Error?X$:Error(String(X$)))})},oK*2**(G-1));return}X(dK(p.code,p.reason))}})};$.signal?.addEventListener("abort",()=>{_=!0,Y(),X()},{once:!0}),await P();let V={[Symbol.asyncIterator](){return V},next:async()=>{if(v.length>0)return{value:v.shift(),done:!1};if(D){if(I)throw I;return{value:void 0,done:!0}}return new Promise((O)=>{U.push(O)}).then((O)=>{if(O.done&&I)throw I;return O})},return:async()=>{return _=!0,Y(),X(),{value:void 0,done:!0}},throw:async(O)=>{throw _=!0,Y(),X(O instanceof Error?O:Error(String(O))),O}};return V},nL=($)=>{let v=(()=>{if(typeof $==="string")return $;if($ instanceof ArrayBuffer)return new TextDecoder().decode($);return null})();if(!v)return[];try{let U=iK.safeParse(JSON.parse(v));if(!U.success)return[];return U.data.data}catch{return[]}},dL=($)=>{return![1000,1001,1008,4001,4003,4004].includes($)},dK=($,v)=>{if(v)return Error(v);let U={1000:"Normal closure",1001:"Endpoint going away",1002:"Protocol error",1003:"Unsupported data",1006:"Connection closed abnormally (no close frame received)",1007:"Invalid payload data",1008:"Policy violation",1009:"Message too big",1010:"Missing extension",1011:"Internal server error",1015:"TLS handshake failure",4001:"Authentication failed - check your credential",4003:"Forbidden - credential may not have access to this project",4004:"Project not found"}[$]??`Unknown close code: ${$}`;return Error(`Connection closed: ${U}`)},oL=async($,v,U,D=3,_=1e4)=>{let I;for(let G=0;G<=D;G+=1){let J=new AbortController,X=globalThis.setTimeout(()=>J.abort(),_);try{let Q=await $(v,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(U),signal:J.signal});if(Q.ok)return;let Y=await Q.text();if(Q.status===401||Q.status===403)throw Error("Authentication failed. Check your public key.");if(Q.status>=400&&Q.status<500&&Q.status!==429)throw Error(`Client error (${Q.status}): ${Y}`);I=Error(Q.status===429?`Rate limited (429): ${Y}`:`Server error (${Q.status}): ${Y}`)}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);if(Y.startsWith("Authentication failed")||Y.startsWith("Client error ("))throw Q instanceof Error?Q:Error(Y);I=Q instanceof Error&&Q.name==="AbortError"?Error("Request timed out"):Q instanceof Error?Q:Error(String(Q))}finally{globalThis.clearTimeout(X)}if(G<D)await pL(oK*2**G)}throw Error(`Failed after ${D+1} attempts: ${I?.message??"Unknown error"}`)},tL=($)=>{return $.resourceLogs?.reduce((v,U)=>v+(U.scopeLogs?.reduce((D,_)=>D+(_.logRecords?.length??0),0)??0),0)??0},pL=async($)=>{await new Promise((v)=>globalThis.setTimeout(v,$))},$7=($,v,U)=>{return new D$("BAD_REQUEST",{message:v,data:{operationId:$,missingContext:U}})};var Gw=L(()=>{qv();_w();nK();k$();AL=w.object({projectId:w.string().uuid().optional().describe("Project to tail logs for. Auto-filled from CLI and SDK context when omitted."),filters:Uw.optional().describe("Optional filters applied by the tail WebSocket service.")}),jL=w.object({publicKey:w.string().min(1).describe("Public key for intake auth. Create or list one via the public key endpoints."),logs:w.custom(($)=>typeof $==="object"&&$!==null).describe("OTLP logs export request payload to send to the intake service.")}),EL=w.object({forwardedCount:w.number().int().nonnegative().describe("Number of log records accepted by the intake request."),failedCount:w.number().int().nonnegative().describe("Number of log records rejected by the intake request.")})});var aL="https://api.sazabi.com",U7="https://api.platform.sazabi.com",D7="sazabi-cli",eL="urn:ietf:params:oauth:grant-type:device_code",v7=($)=>{if($&&typeof $==="object")return $;return{}},I7=($)=>{let v=VD(new ZD(a9,{url:sL($.apiBaseUrl??aL),headers:async()=>new Headers({authorization:`Bearer ${await $.credentialProvider.getToken()}`}),fetch:$.fetch,customErrorResponseBodyDecoder:(D,_)=>{let I=GN(D);if(!I)return null;return new D$(I.code,{message:I.message,status:_.status,data:{operationId:I.operationId,missingContext:I.missingContext}})}})),U=aK({raw:v,credentialProvider:$.credentialProvider,fetch:$.fetch,intakeBaseUrl:$.intakeBaseUrl,tailBaseUrl:$.tailBaseUrl,webSocket:$.webSocket});return{raw:v,me:async()=>v.me({}),logs:{...U,query:async(D={})=>v.logs.query(await s$($.credentialProvider,D,y4.operationId))},organizations:{list:async()=>v.organizations.list({}),get:async(D)=>v.organizations.get(D),update:async(D)=>v.organizations.update(await vN($.credentialProvider,D))},members:{list:async(D={})=>v.members.list(await CU($.credentialProvider,D)),updateRole:async(D)=>v.members.updateRole(await CU($.credentialProvider,D)),remove:async(D)=>{let _=await CU($.credentialProvider,D);return v.members.remove({params:{userId:_.userId},query:{organizationId:_.organizationId}})}},publicKeys:{list:async(D={})=>v.publicKeys.list(await s$($.credentialProvider,D,E4.operationId)),get:async(D)=>v.publicKeys.get(await s$($.credentialProvider,D,x4.operationId)),create:async(D)=>v.publicKeys.create(await s$($.credentialProvider,D,R4.operationId)),update:async(D)=>v.publicKeys.update(await s$($.credentialProvider,D,C4.operationId)),delete:async(D)=>{let _=await s$($.credentialProvider,D,u4.operationId);return v7(await v.publicKeys.delete({params:{keyId:_.keyId},query:{projectId:_.projectId}}))}},secretKeys:{list:async(D={})=>v.secretKeys.list(D),get:async(D)=>v.secretKeys.get(D),create:async(D)=>v.secretKeys.create(D),update:async(D)=>v.secretKeys.update(D),delete:async(D)=>v7(await v.secretKeys.delete({params:{keyId:D.keyId}}))},search:{threads:async(D)=>v.search.threads(await s$($.credentialProvider,D,c4.operationId)),messages:async(D)=>v.search.messages(await s$($.credentialProvider,D,h4.operationId))},projects:{list:async(D={})=>v.projects.list(await $N($.credentialProvider,D)),get:async(D)=>v.projects.get(D)},messages:{list:async(D)=>v.messages.list(D),append:async(D)=>_7(v,await v.messages.append(IN(D)))},threads:{list:async(D={})=>v.threads.list(await _N($.credentialProvider,D)),get:async(D)=>v.threads.get(D),getStatus:async(D)=>v.threads.getStatus(D),create:async(D)=>_7(v,await v.threads.create(await DN($.credentialProvider,D))),update:async(D)=>v.threads.update(D)},runs:{list:async(D={})=>v.runs.list(await UN($.credentialProvider,D)),listForThread:async(D)=>v.runs.listForThread(D),get:async(D)=>v.runs.get(D)},dataSources:{listTypes:async()=>v.dataSources.listTypes({}),connections:{list:async(D={})=>v.dataSources.listConnections(await s$($.credentialProvider,D,A4.operationId)),get:async(D)=>v.dataSources.getConnection(D),create:async(D)=>v.dataSources.createConnection(await s$($.credentialProvider,D,j4.operationId))},streams:{list:async(D)=>v.dataSources.listStreams(D),get:async(D)=>v.dataSources.getStream(D),create:async(D)=>v.dataSources.createStream(D)}}}},G7=async($={})=>{let v=await Q7($.fetch)(w7($.apiBaseUrl??U7,"/device/code"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:$.clientId??D7,...$.scope?{scope:$.scope}:{}})}),U=await v.json();if(!v.ok)throw JN(U,v.status);let D=U;return{deviceCode:m4(D.device_code,"device_code"),userCode:m4(D.user_code,"user_code"),verificationUri:m4(D.verification_uri,"verification_uri"),verificationUriComplete:m4(D.verification_uri_complete,"verification_uri_complete"),expiresIn:Jw(D.expires_in,"expires_in"),interval:Jw(D.interval,"interval")}},J7=async($)=>{let v=await Q7($.fetch)(w7($.apiBaseUrl??U7,"/device/token"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:eL,device_code:$.deviceCode,client_id:$.clientId??D7})}),U=await v.json();if(v.ok){let _=U;return{status:"authorized",accessToken:m4(_.access_token,"access_token"),tokenType:m4(_.token_type,"token_type"),expiresIn:Jw(_.expires_in,"expires_in"),scope:typeof _.scope==="string"?_.scope:""}}let D=X7(U);if(!D)throw Error(`Device authorization failed with status ${v.status}`);if(D.error==="authorization_pending")return{status:"pending"};if(D.error==="slow_down")return{status:"pending",interval:10};if(D.error==="access_denied")return{status:"denied",message:D.errorDescription};if(D.error==="expired_token"||D.error==="invalid_grant")return{status:"expired",message:D.errorDescription};throw Error(D.errorDescription)},sL=($)=>{let v=$.replace(/\/+$/,"");return v.endsWith("/v1")?v:`${v}/v1`},w7=($,v)=>{return`${$.replace(/\/+$/,"")}/api/auth${v}`},$N=async($,v)=>{return CU($,v)},CU=async($,v)=>{let U=v.organizationId??await $.getOrganizationId?.();return U?{...v,organizationId:U}:v},vN=async($,v)=>{let U=v.organizationId??await $.getOrganizationId?.();if(!U)throw new D$("BAD_REQUEST",{message:"Organization ID is required",data:{operationId:"organizations.update",missingContext:["organizationId"]},status:400});return{...v,organizationId:U}},s$=async($,v,U)=>{let D=v.projectId??await $.getProjectId?.();if(!D)throw new D$("BAD_REQUEST",{message:"Project ID is required",data:{operationId:U,missingContext:["projectId"]},status:400});return{...v,projectId:D}},_N=async($,v)=>{let U=v.projectId??await $.getProjectId?.();return U?{...v,projectId:U}:v},UN=async($,v)=>{let U=v.projectId??await $.getProjectId?.();return U?{...v,projectId:U}:v},DN=async($,v)=>{let U=v.projectId??await $.getProjectId?.();return U?{...v,projectId:U}:v},IN=($)=>{return{threadId:$.threadId,message:$.message,wait:$.wait??!0,timeoutSeconds:$.timeoutSeconds??20}},GN=($)=>{if(!$||typeof $!=="object")return null;let v=$;if(typeof v.code!=="string"||typeof v.message!=="string"||typeof v.operationId!=="string")return null;return{code:v.code,message:v.message,operationId:v.operationId,missingContext:Array.isArray(v.missingContext)?v.missingContext.filter((U)=>typeof U==="string"):[]}},X7=($)=>{if(!$||typeof $!=="object")return null;let v=$;if(typeof v.error!=="string"||typeof v.error_description!=="string")return null;return{error:v.error,errorDescription:v.error_description}},JN=($,v)=>{let U=X7($);return Error(U?.errorDescription??`Device authorization failed with status ${v}`)},Q7=($)=>{return $??globalThis.fetch},_7=($,v)=>({result:v,poll:()=>$.runs.get({runId:v.runId}),waitForCompletion:async(U={})=>wN($,v,U)}),wN=async($,v,U)=>{if(v.completed)return v;let D=U.intervalMs??2000,_=Date.now(),I=v;while(!I.completed){if(U.timeoutMs!==void 0&&Date.now()-_>=U.timeoutMs)return I;await XN(D),I=await $.runs.get({runId:I.runId})}return I},XN=async($)=>{await new Promise((v)=>globalThis.setTimeout(v,$))},m4=($,v)=>{if(typeof $==="string")return $;throw Error(`Expected '${v}' to be a string.`)},Jw=($,v)=>{if(typeof $==="number")return $;throw Error(`Expected '${v}' to be a number.`)};var ww=L(()=>{qv();KX();vw();Gw();Gw()});var c$=($)=>({success:!0,value:$}),Tv=($,v,U)=>({success:!1,error:$,...v!==void 0&&{statusCode:v},...U!==void 0&&{errorPayload:U}}),k=($,v,U)=>{if(!$.success){let D=`${v}: ${$.error}`;if(U)return q($.errorPayload??D);return N(D)}return $.value};var e=L(()=>{n()});var YN="https://api.sazabi.com",f=async($)=>{try{return c$(await $())}catch(v){let U=PN(v),D=KN(v),_=v instanceof Error?v.message:String(v);return Tv(_,D,U)}},PN=($)=>{if(!$||typeof $!=="object")return;let v=$;if(typeof v.code!=="string"||typeof v.message!=="string"||!v.data||typeof v.data!=="object")return;let U=v.data;if(typeof U.operationId!=="string")return;return{code:v.code,message:v.message,operationId:U.operationId,missingContext:Array.isArray(U.missingContext)?U.missingContext.filter((D)=>typeof D==="string"):[]}},KN=($)=>{if(!$||typeof $!=="object")return;let v=$;return typeof v.status==="number"?v.status:void 0},Jv=($)=>{let v=I7({apiBaseUrl:$.baseUrl??YN,credentialProvider:{getToken:()=>$.token,getOrganizationId:()=>$.organizationId,getProjectId:()=>$.projectId},intakeBaseUrl:$.intakeBaseUrl,tailBaseUrl:$.tailBaseUrl});return{me:()=>f(()=>v.me()),logs:{tail:(U)=>f(()=>v.logs.tail(U)),forward:(U)=>f(()=>v.logs.forward(U))},organizations:{list:()=>f(()=>v.organizations.list()),get:(U)=>f(()=>v.organizations.get({organizationId:U})),rename:(U,D)=>f(()=>v.organizations.update({organizationId:D,name:U}))},members:{list:(U={})=>f(()=>v.members.list(U)),updateRole:(U,D,_)=>f(()=>v.members.updateRole({organizationId:_,userId:U,role:D})),remove:(U,D)=>f(()=>v.members.remove({organizationId:D,userId:U}))},projects:{list:(U={})=>f(()=>v.projects.list(U)),get:(U)=>f(()=>v.projects.get({projectId:U}))},threads:{list:(U={})=>f(()=>v.threads.list(U)),get:(U)=>f(()=>v.threads.get({threadId:U})),create:(U)=>f(()=>v.threads.create(U)),getStatus:(U)=>f(()=>v.threads.getStatus({threadId:U})),update:(U,D)=>f(()=>v.threads.update({threadId:U,status:D}))},messages:{list:(U,D={})=>f(()=>v.messages.list({threadId:U,...D})),append:(U,D,_,I)=>f(()=>v.messages.append({threadId:U,message:D,wait:_,timeoutSeconds:I}))},runs:{get:(U)=>f(()=>v.runs.get({runId:U}))},search:{threads:(U)=>f(()=>v.search.threads(U)),messages:(U)=>f(()=>v.search.messages(U))},publicKeys:{list:(U)=>f(()=>v.publicKeys.list(U)),get:(U,D)=>f(()=>v.publicKeys.get(D?{keyId:U,projectId:D}:{keyId:U})),create:(U)=>f(()=>v.publicKeys.create(U)),update:(U)=>f(()=>v.publicKeys.update(U)),delete:(U)=>f(()=>v.publicKeys.delete(U))},secretKeys:{list:(U)=>f(()=>v.secretKeys.list(U)),get:(U)=>f(()=>v.secretKeys.get({keyId:U})),create:(U)=>f(()=>v.secretKeys.create(U)),update:(U)=>f(()=>v.secretKeys.update(U)),delete:(U)=>f(()=>v.secretKeys.delete(U))},dataSources:{listTypes:()=>f(()=>v.dataSources.listTypes()),connections:{list:(U)=>f(()=>v.dataSources.connections.list(U)),get:(U)=>f(()=>v.dataSources.connections.get({connectionId:U})),create:(U)=>f(()=>v.dataSources.connections.create(U))},streams:{list:(U)=>f(()=>v.dataSources.streams.list({connectionId:U})),get:(U)=>f(()=>v.dataSources.streams.get({streamId:U})),create:(U)=>f(()=>v.dataSources.streams.create(U))}}}};var s6=L(()=>{ww();e()});var Y7;var P7=L(()=>{Y7={version:2,activeProfile:"default",profiles:{default:{}}}});import*as wv from"node:fs";import*as K7 from"node:os";import*as Yw from"node:path";var B$=($)=>{if($===void 0||$===null)return;if(typeof $==="string")return $.length>0?$:void 0;return},Xw,l4,VN=()=>{if(!wv.existsSync(Xw))wv.mkdirSync(Xw,{recursive:!0,mode:448})},Qw,V7=($)=>{Qw=$},O7=($)=>({token:B$($.token),activeOrganizationId:B$($.activeOrganizationId??$.organizationId),organizationName:B$($.organizationName),activeProjectId:B$($.activeProjectId??$.defaultProjectId),apiBaseUrl:B$($.apiBaseUrl),webBaseUrl:B$($.webBaseUrl),intakeBaseUrl:B$($.intakeBaseUrl),tailBaseUrl:B$($.tailBaseUrl),apiDomain:B$($.apiDomain),webDomain:B$($.webDomain),intakeDomain:B$($.intakeDomain),tailDomain:B$($.tailDomain),forwardPublicKey:B$($.forwardPublicKey)}),ON=($)=>({version:2,activeProfile:"default",profiles:{default:O7($)}}),WN=($)=>{let v=B$($.activeProfile)??"default",U=typeof $.profiles==="object"&&$.profiles!==null?$.profiles:{},D={};for(let[_,I]of Object.entries(U)){if(typeof I!=="object"||I===null)continue;D[_]=O7(I)}if(!D[v])D[v]={};return{version:2,activeProfile:v,profiles:D}},s=()=>{try{if(!wv.existsSync(l4))return c$(Y7);let $=wv.readFileSync(l4,"utf-8"),v=JSON.parse($),U=typeof v.version==="number"?v.version:void 0;if(U!==void 0&&U>2)return Tv("Settings file requires a newer CLI version. Please upgrade.");if(U===2)return c$(WN(v));let D=ON(v),_=J$(D);if(!_.success)return _;return c$(D)}catch($){let v=$ instanceof Error?$.message:String($);return Tv(`Failed to read settings: ${v}`)}},J$=($)=>{try{return VN(),wv.writeFileSync(l4,JSON.stringify($,null,2),{encoding:"utf-8",mode:384}),c$(void 0)}catch(v){let U=v instanceof Error?v.message:String(v);return Tv(`Failed to write settings: ${U}`)}},Xv=($,v)=>{if(v)return v;if(Qw)return Qw;let U=process.env.SAZABI_PROFILE?.trim();if(U)return U;return $.activeProfile??"default"},l$=($,v)=>{let U=Xv($,v),D=$.profiles[U];if(D)return c$(D);if(U==="default")return c$({});return Tv(`Profile '${U}' does not exist. Run 'sazabi profiles create ${U}' first.`)},Qv=()=>{let $=s();if(!$.success)return $;return l$($.value)},E$=($,v,U)=>{let D=Xv($,U);if(!$.profiles[D])return Tv(`Profile '${D}' does not exist. Run 'sazabi profiles create ${D}' first.`);return c$({...$,profiles:{...$.profiles,[D]:{...$.profiles[D],...v}}})};var h$=L(()=>{P7();e();Xw=Yw.join(K7.homedir(),".sazabi"),l4=Yw.join(Xw,"settings.json")});var $v=($)=>{let{cliFlag:v,globalUrl:U,globalDomain:D,buildUrlFromDomain:_,defaultUrl:I}=$;if(v)return v;let G=process.env.SAZABI_API_URL?.trim();if(G)return G;if(U)return U;if(D)return _(D);return I},R=($)=>{let{tokenFlag:v,organizationIdFlag:U,projectIdFlag:D,jsonMode:_}=$,I=v?.trim(),G=process.env.SAZABI_TOKEN?.trim(),J=process.env.SAZABI_ORGANIZATION_ID?.trim(),X=process.env.SAZABI_PROJECT_ID?.trim(),Q=k(Qv(),"Failed to read settings",_),Y=Q.token?.trim(),P=(I&&I.length>0?I:void 0)||(G&&G.length>0?G:void 0)||Y,V=I&&I.length>0?"flag":G&&G.length>0?"environment":"settings";if(!P||P.length===0){if(_)return q("Not authenticated. Set SAZABI_TOKEN, pass --token, run 'sazabi auth login', or run 'sazabi auth save <token>'.");return N("Not authenticated. Set SAZABI_TOKEN, pass --token, run 'sazabi auth login', or run 'sazabi auth save <token>'.")}let O,S;if(U)O=U,S="flag";else if(J&&J.length>0)O=J,S="environment";else if(Q.activeOrganizationId)O=Q.activeOrganizationId,S="settings";let B,h;if(D)B=D,h="flag";else if(X&&X.length>0)B=X,h="environment";else if(Q.activeProjectId)B=Q.activeProjectId,h="settings";return{token:P,type:"token",projectId:B,organizationId:O,tokenSource:V,organizationSource:S,projectSource:h}},y=($)=>{let v=k(Qv(),"Failed to read settings",$.jsonMode),U=$v({cliFlag:$.apiBaseUrlFlag,globalUrl:v.apiBaseUrl,globalDomain:v.apiDomain,buildUrlFromDomain:(D)=>`https://api.${D}`,defaultUrl:"https://api.sazabi.com"});return Jv({token:$.token,baseUrl:U,organizationId:$.organizationId,projectId:$.projectId})},W7,Pw,uU=async($)=>{let v=k(Qv(),"Failed to read settings",$.jsonMode),U=$v({cliFlag:$.apiBaseUrlFlag,globalUrl:v.apiBaseUrl,globalDomain:v.apiDomain,buildUrlFromDomain:(X)=>`https://api.${X}`,defaultUrl:"https://api.sazabi.com"}),D=`${$.token}@${U}@${$.projectId??""}`,_=W7.get(D);if(_)return _;let I=Pw.get(D);if(I)return I;if(!$.projectId){if($.jsonMode)return q("Project ID is required. Run 'sazabi projects use <project-id>' or set SAZABI_PROJECT_ID.");return N("Project ID is required. Run 'sazabi projects use <project-id>' or set SAZABI_PROJECT_ID.")}let G=$.projectId,J=(async()=>{let Q=await Jv({token:$.token,baseUrl:U,projectId:G}).projects.get(G),P=k(Q,"Failed to fetch project info",$.jsonMode).project;return W7.set(D,P),P})();Pw.set(D,J);try{return await J}finally{Pw.delete(D)}},$1=($)=>{if($)return $;let v=k(Qv(),"Failed to read settings");if(v.webBaseUrl)return v.webBaseUrl;if(v.webDomain)return`https://app.${v.webDomain}`;if(v.apiDomain)return`https://app.${v.apiDomain}`;if(v.apiBaseUrl?.includes("sazabi.dev"))return"https://app.sazabi.dev";return"https://app.sazabi.com"},yU=($,v,U)=>{return`${$1(U)}/projects/${$}/threads/${v}`},L7=($,v)=>{return`https://otlp.${v}.intake.${$}`};var w$=L(()=>{n();s6();e();h$();W7=new Map,Pw=new Map});var iU,_V=($)=>{iU.set($.name,$)},nU=($)=>{return iU.get($)},_1=()=>{return Array.from(iU.values())},UV=($)=>{return iU.has($)};var kw=L(()=>{iU=new Map});async function Sw($){let v=await $.publicKeys.list({limit:20});if(!v.success)return[];return v.value.publicKeys.map((U)=>({value:U.id,description:U.name}))}async function Bw($){let v=await $.secretKeys.list({limit:20});if(!v.success)return[];return v.value.secretKeys.map((U)=>({value:U.id,description:U.name}))}async function h3($){let v=await $.dataSources.connections.list();if(!v.success)return[];return v.value.connections.map((U)=>({value:U.id,description:U.displayName??void 0}))}async function JV($){let v=await $.members.list();if(!v.success)return[];return v.value.members.map((U)=>({value:U.userId,description:U.name??U.email}))}var f3=3000,c3,wV=async($,v,U)=>{try{let D=c3[$]?.[v];if(!D)return[];let _=Qv();if(!_.success)return[];let I=_.value,G=process.env.SAZABI_TOKEN?.trim()||I.token?.trim();if(!G)return[];let J=$v({globalUrl:I.apiBaseUrl,globalDomain:I.apiDomain,buildUrlFromDomain:(Y)=>`https://api.${Y}`,defaultUrl:"https://api.sazabi.com"}),X=Jv({token:G,baseUrl:J,organizationId:I.activeOrganizationId,projectId:I.activeProjectId});return(await Promise.race([D(X),new Promise((Y)=>setTimeout(()=>Y([]),f3))])).filter((Y)=>Y.value.startsWith(U))}catch{return[]}};var XV=L(()=>{s6();w$();h$();c3={threads:{get:async($)=>{let v=await $.threads.list({limit:20});if(!v.success)return[];return v.value.threads.map((U)=>({value:U.id,description:U.title??void 0}))}},projects:{use:async($)=>{let v=await $.projects.list();if(!v.success)return[];return v.value.projects.map((U)=>({value:U.id,description:U.name}))}},organizations:{use:async($)=>{let v=await $.organizations.list();if(!v.success)return[];return v.value.organizations.map((U)=>({value:U.id,description:U.name}))},rename:async($)=>{let v=await $.organizations.list();if(!v.success)return[];return v.value.organizations.map((U)=>({value:U.id,description:U.name}))}},"public-keys":{get:Sw,update:Sw,delete:Sw},"secret-keys":{get:Bw,update:Bw,delete:Bw},"data-sources":{"get-connection":h3},members:{"update-role":JV,remove:JV}}});var YV={};i$(YV,{parseCompletionContext:()=>l3,getCompletions:()=>i3});var r3,m3,l3=($)=>{let v=$.length>0?$:[""],U=v.length-1,D=v[U]??"";return{words:v,currentIndex:U,partial:D}},i3=async($)=>{let{words:v,currentIndex:U,partial:D}=$,_=v[U-1];if(_==="--profile")return t3(D);let I=o3(v),G=Math.max(0,I.length-(v.length-U));if(G===0)return n3(D);let J=I[0]??"",X=nU(J);if(!X)return[];if(G===1&&X.subcommands){if(D.startsWith("-"))return QV(X.options,I);return d3(X,D)}let Q=X.subcommands?I[1]:void 0,P=(Q?X.subcommands?.[Q]:void 0)?.options??X.options;if(D.startsWith("-"))return QV(P,I);if(_?.startsWith("--")){let V=_.slice(2);if(P?.[V]?.type==="string"){let S=`${J}:${Q??""}`,B=m3[S]?.[V]??r3[V];if(B)return B.filter((h)=>h.startsWith(D)).map((h)=>({value:h}));return[]}}return wV(J,Q??"",D)},n3=($)=>{let U=_1().filter((_)=>_.name.startsWith($)).map((_)=>({value:_.name,description:_.description})),D=[{value:"--help",description:"Show help"},{value:"--version",description:"Show version"},{value:"--profile",description:"Use a named profile"}];for(let _ of D)if(_.value.startsWith($))U.push(_);return U},d3=($,v)=>{if(!$.subcommands)return[];return Object.values($.subcommands).filter((U)=>U.name.startsWith(v)).map((U)=>({value:U.name,description:U.description}))},QV=($,v)=>{let U=v[v.length-1]??"",D=new Set(v.filter((I)=>I.startsWith("--")).map((I)=>I.replace(/=.*/,""))),_=[];if(!D.has("--help")&&"--help".startsWith(U))_.push({value:"--help",description:"Show help"});if(!D.has("--profile")&&"--profile".startsWith(U))_.push({value:"--profile",description:"Use a named profile"});if(!$)return _;for(let[I,G]of Object.entries($)){let J=`--${I}`;if(D.has(J))continue;if(!J.startsWith(U))continue;_.push({value:J,description:G.description})}return _},o3=($)=>{let v=[];for(let U=0;U<$.length;U++){let D=$[U];if(D==="--profile"&&U+1<$.length)U++;else if(D.startsWith("--profile="));else v.push(D)}return v},t3=($)=>{try{let v=s();if(!v.success)return[];return Object.keys(v.value.profiles).filter((U)=>U.startsWith($)).map((U)=>({value:U,description:U===v.value.activeProfile?"active":void 0}))}catch{return[]}};var PV=L(()=>{kw();h$();XV();r3={status:["regular","archived"],format:["json","text"]},m3={"members:update-role":{role:["admin","member"]},"messages:search":{role:["user","assistant"]},"messages:list":{role:["user","assistant"]}}});n();n();ww();import{spawn as LN}from"node:child_process";n();import{parseArgs as QN}from"node:util";var j=($,v,U={})=>{let D=QN({args:$,options:v,allowPositionals:Boolean(U.allowPositionals),strict:!1,tokens:!0}),_=Object.hasOwn(v,"json")&&D.values.json===!0,I=new Set(Object.keys(v)),G=new Set(Object.entries(v).map(([,X])=>X.short).filter((X)=>Boolean(X))),J=[];if(Array.isArray(D.tokens))for(let X of D.tokens){if(X.kind!=="option")continue;let Q=X.name,Y=Q.length>1;if(!(I.has(Q)||!Y&&G.has(Q))){let V=Y?`--${Q}`:`-${Q}`;if(!J.includes(V))J.push(V)}}for(let X of Object.keys(D.values))if(!I.has(X)){let Q=X.length>1?`--${X}`:`-${X}`;if(!J.includes(Q))J.push(Q)}if(J.length>0){let X=`Unknown option${J.length>1?"s":""}: ${J.join(", ")}`;if(_)q(X);N(X)}for(let[X,Q]of Object.entries(v))if(Q.type==="string"&&D.values[X]===!0){let P=`Option ${X.length===1?`-${X}`:`--${X}`} requires a value`;if(_)q(P);N(P)}for(let[X,Q]of Object.entries(v)){let Y=D.values[X];if(Q.type==="string"&&typeof Y==="string"){if(Y.startsWith("--")||Y.length===2&&Y[0]==="-"&&/[a-zA-Z]/.test(Y.charAt(1))){let O=`Option ${X.length===1?`-${X}`:`--${X}`} received "${Y}" as its value. Did you forget to provide a value?`;if(_)q(O);N(O)}}}return{values:D.values,positionals:D.positionals}};w$();var fU=($,v)=>{let U=$?.json;if(!U||U.type!=="boolean")throw Error(`${v} must include a boolean --json option (enforced by CommandBuilder)`)};class N7{name;description;handler;subcommands;options;examples;positionalArgs;allowNoJson=!1;constructor($,v,U){this.name=$,this.description=v,this.handler=U}withOptions($){return this.options=$,this}withSubcommands($){return this.subcommands=$,this}withExamples($){return this.examples=$,this}withPositionalArgs($){return this.positionalArgs=$,this}build(){if(!this.handler&&!this.subcommands)throw Error(`Subcommand "${this.name}" must have either a handler or subcommands`);if(!this.allowNoJson&&this.handler)fU(this.options,`Subcommand "${this.name}"`);if(!this.allowNoJson&&this.subcommands){for(let[$,v]of Object.entries(this.subcommands))if(!v.subcommands)fU(v.options,`Subcommand "${this.name} ${$}"`)}return{name:this.name,description:this.description,handler:this.handler,subcommands:this.subcommands,options:this.options,examples:this.examples,positionalArgs:this.positionalArgs}}allowWithoutJson(){return this.allowNoJson=!0,this}}class q7{name;description;handler;subcommands;options;examples;positionalArgs;allowNoJson=!1;constructor($,v){this.name=$,this.description=v}withHandler($){return this.handler=$,this}withSubcommands($){return this.subcommands=$,this}withOptions($){return this.options=$,this}withExamples($){return this.examples=$,this}withPositionalArgs($){return this.positionalArgs=$,this}build(){if(!this.handler&&!this.subcommands)throw Error(`Command "${this.name}" must have either a handler or subcommands`);if(!this.allowNoJson){if(this.handler)fU(this.options,`Command "${this.name}"`);if(this.subcommands)for(let[$,v]of Object.entries(this.subcommands)){if(v.subcommands)continue;fU(v.options,`Subcommand "${this.name} ${$}"`)}}return{name:this.name,description:this.description,handler:this.handler,subcommands:this.subcommands,options:this.options,examples:this.examples,positionalArgs:this.positionalArgs}}allowWithoutJson(){return this.allowNoJson=!0,this}}var o=($,v)=>{return new q7($,v)},z=($,v,U)=>{return new N7($,v,U)};e();h$();var i4=($)=>{if($==="flag")return"from flag";if($==="environment")return"from environment";return"from settings"},NN=async($={})=>{let v=R({jsonMode:$.json}),U=y({token:v.token,organizationId:v.organizationId,projectId:v.projectId,apiBaseUrlFlag:$.apiBaseUrl,jsonMode:$.json}),D=k(await U.me(),"Failed to fetch authentication details",$.json);if($.json){M({credential:D,activeOrganizationId:v.organizationId,activeProjectId:v.projectId,tokenSource:v.tokenSource,organizationSource:v.organizationSource,projectSource:v.projectSource});return}if(Y$("Authentication"),D.credentialType==="user"){_$({Type:`User token (${i4(v.tokenSource)})`,User:D.user.name??D.user.email,Email:D.user.email,"Active Organization":v.organizationId&&v.organizationSource?`${v.organizationId} (${i4(v.organizationSource)})`:G$("(none)"),"Active Project":v.projectId&&v.projectSource?`${v.projectId} (${i4(v.projectSource)})`:G$("(none)"),Organizations:D.organizations.length.toString(),"Dashboard URL":$1()});return}if(D.credentialType==="secret"){_$({Type:`Secret key (${i4(v.tokenSource)})`,Organization:D.organization.name,"Key Name":D.keyName,"Active Project":v.projectId&&v.projectSource?`${v.projectId} (${i4(v.projectSource)})`:G$("(none)"),"Dashboard URL":$1()});return}_$({Type:`Partner key (${i4(v.tokenSource)})`,Superorganization:D.superorganization.name,"Dashboard URL":$1()})},qN=async($,v={})=>{let U=$.trim();if(!U){if(v.json)return q("Token is required.");return N("Token is required.")}let D=k(s(),"Failed to read settings",v.json);await k7({token:U,options:v,cliSettings:D,status:"saved"})},kN=($)=>{let v=process.platform,U,D;if(v==="darwin")U="open",D=[$];else if(v==="win32")U="cmd",D=["/c","start","",$];else U="xdg-open",D=[$];let _=LN(U,D,{detached:!0,stdio:"ignore"});_.on("error",()=>{}),_.unref()},HN=($)=>new Promise((v)=>setTimeout(v,$)),FN=async($={})=>{let v=k(s(),"Failed to read settings",$.json),U=Xv(v),D=v.profiles[U]??{},_=ZN(D,$.apiBaseUrl),I=MN(_,$.authBaseUrl),G;try{G=await G7({apiBaseUrl:I})}catch(Y){let P=Y instanceof Error?Y.message:String(Y);if($.json)return q(`Failed to initiate login: ${P}`);return N(`Failed to initiate login: ${P}`)}let J=TN(G.verificationUriComplete,$.webBaseUrl),X=new Date(Date.now()+G.expiresIn*1000),Q=G.interval*1000;if(!$.json)r(),Y$("Login to Sazabi"),r(),r$("Enter this code in your browser:"),r(),r$(O$.bold(G.userCode),4),r(),r$(`Opening ${O$.info(J)}`),r(),kN(J),c("Waiting for authorization...");while(new Date<X){await HN(Q);try{let Y=await J7({apiBaseUrl:I,deviceCode:G.deviceCode});if(Y.status==="pending"){Q=(Y.interval??G.interval)*1000;continue}if(Y.status==="denied"){if($.json)return q("Authorization was denied.");return r(),N("Authorization was denied.")}if(Y.status==="expired"){if($.json)return q("Authorization request expired. Please try again.");return r(),N("Authorization request expired. Please try again.")}await k7({token:Y.accessToken,options:$,cliSettings:v,status:"authorized"});return}catch(Y){let P=Y instanceof Error?Y.message:String(Y);if($.json)return q(`Authorization failed: ${P}`);return r(),N(`Authorization failed: ${P}`)}}if($.json)return q("Authorization request expired. Please try again.");return r(),N("Authorization request expired. Please try again.")},bN=($)=>{let v=k(s(),"Failed to read settings",$.json),U=k(l$(v),"Failed to resolve profile",$.json),D=Boolean(U.token),_=k(E$(v,{token:void 0,activeOrganizationId:void 0,organizationName:void 0,activeProjectId:void 0}),"Failed to update profile",$.json);if(k(J$(_),"Failed to remove credentials",$.json),$.json){M({removed:D});return}if(D){u("Logged out successfully.");return}c("No credentials were saved.")},k7=async({token:$,options:v,cliSettings:U,status:D})=>{let _=y({token:$,apiBaseUrlFlag:v.apiBaseUrl,jsonMode:v.json}),I=k(await _.me(),"Failed to resolve authenticated context",v.json);if(D==="authorized"&&I.credentialType!=="user"){if(v.json)return q("Expected a user session from device authorization.");return N("Expected a user session from device authorization.")}let G=Xv(U),J=U.profiles[G]?U:{...U,profiles:{...U.profiles,[G]:{}}},X=J.profiles[G],Q=await gN({client:_,credential:I,currentProjectId:X.activeProjectId,jsonMode:v.json}),Y=k(E$(J,{token:$,activeOrganizationId:Q.activeOrganizationId,organizationName:Q.activeOrganizationName,activeProjectId:Q.activeProjectId,apiBaseUrl:v.apiBaseUrl??X.apiBaseUrl}),"Failed to update profile",v.json);if(k(J$(Y),"Failed to save credentials",v.json),v.json){M({status:D,credential:I,activeOrganizationId:Q.activeOrganizationId,activeProjectId:Q.activeProjectId,projects:Q.projects});return}if(r(),u(D==="authorized"?"Successfully authenticated!":"Saved token."),r(),BN({credential:I,activeOrganizationName:Q.activeOrganizationName,activeProjectId:Q.activeProjectId,projects:Q.projects}),Q.projects.length>0){r(),Y$("Available Projects");for(let P of Q.projects){let O=P.id===Q.activeProjectId?O$.success(" (active)"):"";r$(`${P.name} (${P.region})${O}`)}}},gN=async({client:$,credential:v,currentProjectId:U,jsonMode:D})=>{if(v.credentialType==="partner")return{projects:[]};let _=v.credentialType==="user"?v.activeOrganizationId??v.organizations[0]?.id:v.organization.id,I=v.credentialType==="user"?v.organizations.find((J)=>J.id===_)?.name:v.organization.name,G=_?k(await $.projects.list({organizationId:_}),"Failed to fetch projects",D).projects:[];return{activeOrganizationId:_,activeOrganizationName:I,activeProjectId:SN(G,U),projects:G}},SN=($,v)=>{if(v&&$.some((U)=>U.id===v))return v;return $[0]?.id},BN=({credential:$,activeOrganizationName:v,activeProjectId:U,projects:D})=>{if($.credentialType==="user"){_$({Type:"User token",User:$.user.name??$.user.email,Organizations:$.organizations.length.toString(),"Active Organization":v??"(none)","Active Project":D.find((_)=>_.id===U)?.name??"(none)"});return}if($.credentialType==="secret"){_$({Type:"Secret key",Organization:$.organization.name,"Key Name":$.keyName,"Active Project":D.find((_)=>_.id===U)?.name??"(none)"});return}_$({Type:"Partner key",Superorganization:$.superorganization.name})},ZN=($,v)=>{return $v({cliFlag:v,globalUrl:$.apiBaseUrl,globalDomain:$.apiDomain,buildUrlFromDomain:(U)=>`https://api.${U}`,defaultUrl:"https://api.sazabi.com"})},MN=($,v)=>{if(v)return v;try{let U=new URL($);if(["localhost","127.0.0.1"].includes(U.hostname)&&["15005","15009"].includes(U.port))return U.port="15001",U.toString().replace(/\/$/,"");if(U.hostname==="api.sazabi.com")return U.hostname="api.platform.sazabi.com",U.toString().replace(/\/$/,"");if(U.hostname==="api.sazabi.dev")return U.hostname="api.platform.sazabi.dev",U.toString().replace(/\/$/,"");return U.toString().replace(/\/$/,"")}catch{return $}},TN=($,v)=>{if(!v)return $;let U=new URL($),D=new URL(v);return U.protocol=D.protocol,U.host=D.host,U.toString()},H7=o("auth","").withSubcommands({login:z("login","Authenticate via browser",async($)=>{let{values:v,positionals:U}=j($,{json:{type:"boolean"},"api-base-url":{type:"string"},"auth-base-url":{type:"string"},"web-base-url":{type:"string"}},{allowPositionals:!0});if(U.length>0){let D=U.join(", ");if(v.json)return q(`Unexpected arguments: ${D}`);return N(`Unexpected arguments: ${D}`)}await FN({json:v.json,apiBaseUrl:v["api-base-url"],authBaseUrl:v["auth-base-url"],webBaseUrl:v["web-base-url"]})}).withOptions({json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override public API base URL"},"auth-base-url":{type:"string",description:"Override Better Auth API base URL"},"web-base-url":{type:"string",description:"Override web app base URL"}}).withExamples(["sazabi auth login # Authenticate via browser","sazabi auth login --api-base-url http://localhost:15009 --auth-base-url http://localhost:15001 --web-base-url https://localhost:5173 # Authenticate against local development"]).build(),save:z("save","Save an existing bearer token",async($)=>{let{values:v,positionals:U}=j($,{json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),D=U[0];if(!D){if(v.json)return q("Token is required.");return N("Token is required.")}if(U.length>1){let _=U.slice(1).join(", ");if(v.json)return q(`Unexpected arguments: ${_}`);return N(`Unexpected arguments: ${_}`)}await qN(D,{json:v.json,apiBaseUrl:v["api-base-url"]})}).withPositionalArgs("<token>").withOptions({json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi auth save sazabi_secret_xxx # Save a secret key for future commands","sazabi auth save session_token_xxx --api-base-url http://localhost:15009 # Save a token against local development"]).build(),logout:z("logout","Remove saved credentials",async($)=>{let{values:v,positionals:U}=j($,{json:{type:"boolean"}},{allowPositionals:!0});if(U.length>0){let D=U.join(", ");if(v.json)return q(`Unexpected arguments: ${D}`);return N(`Unexpected arguments: ${D}`)}bN({json:v.json})}).withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(["sazabi auth logout # Remove saved credentials"]).build(),whoami:z("whoami","Display current authentication context",async($)=>{let{values:v,positionals:U}=j($,{json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0});if(U.length>0){let D=U.join(", ");if(v.json)return q(`Unexpected arguments: ${D}`);return N(`Unexpected arguments: ${D}`)}await NN({json:v.json,apiBaseUrl:v["api-base-url"]})}).withOptions({json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi auth whoami # Show current context","sazabi auth whoami --json # Output as JSON"]).build()}).withExamples(["sazabi auth login # Authenticate via browser","sazabi auth save sazabi_secret_xxx # Save an existing token","sazabi auth logout # Remove saved credentials","sazabi auth whoami # Show current context"]).build();n();var F7=()=>`
397
+ `.trim()});var A9,_L,UL,PY,j9,E9,KY,VY,$U,OY,WY,A4,LY,NY,vU,qY,kY,j4,HY,FY,_U,bY,gY,UU,SY,BY,DU,DL;var x9=L(()=>{k$();S$();QY();YY();A9=w.enum(["vercel","cloudflare","railway","render","fly_io","heroku","netlify","supabase","planetscale","digital_ocean","inngest","trigger_dev","temporal","mastra","langchain","daytona","e2b","cloudwatch","convex","datadog","sentry","openrouter","posthog","gcl","gcp","otel"]),_L=w.enum(["pending","provisioning","active","error"]),UL=w.object({name:w.string().describe("Field name used as the JSON key in metadata."),type:w.string().describe('Zod type name, e.g. "string", "boolean", "enum".'),required:w.boolean().describe("Whether the field is required."),sensitive:w.boolean().describe("Whether the field contains a secret and will be encrypted."),description:w.string().nullable().describe("Human-readable description of the field.")}),PY=w.object({id:w.string().describe("Data source type identifier."),name:w.string().describe("Human-readable display name."),metadataFields:w.array(UL).describe("Fields required in the metadata object when creating a connection."),setupSkill:w.string().nullable().describe("Markdown setup skill for AI agents. Null when no skill is available.")}),j9=w.object({id:w.string().uuid(),projectId:w.string().uuid(),dataSourceType:A9,displayName:w.string().nullable(),createdAt:w.string().datetime()}),E9=w.object({id:w.string().uuid(),connectionId:w.string().uuid(),displayName:w.string(),config:w.record(w.string(),w.unknown()),status:_L,errorMessage:w.string().nullable(),createdAt:w.string().datetime()}),KY=w.object({}),VY=w.object({types:w.array(PY)}),$U=T({operationId:"dataSources.listTypes",description:"List all supported data source types with their metadata requirements.",backend:"api",route:{method:"GET",path:"/data-sources/types",tags:["Data Sources"]},input:KY,output:VY,pagination:"none",async:"sync"}),OY=w.object({projectId:w.string().uuid().optional().describe("Project to list connections for. Auto-filled from SDK context when omitted."),dataSourceType:A9.optional().describe("Filter connections by data source type.")}),WY=w.object({connections:w.array(j9)}),A4=T({operationId:"dataSources.listConnections",description:"List data source connections within one project.",backend:"api",route:{method:"GET",path:"/data-sources/connections",tags:["Data Sources"]},input:OY,output:WY,pagination:"none",async:"sync"}),LY=w.object({connectionId:w.string().uuid().describe("Connection ID to fetch.")}),NY=w.object({connection:j9}),vU=T({operationId:"dataSources.getConnection",description:"Get one data source connection by ID.",backend:"api",route:{method:"GET",path:"/data-sources/connections/{connectionId}",tags:["Data Sources"]},input:LY,output:NY,pagination:"none",async:"sync"}),qY=w.object({projectId:w.string().uuid().optional().describe("Project to create the connection in. Auto-filled from SDK context when omitted."),dataSourceType:A9.describe("Data source type identifier."),metadata:w.record(w.string(),w.unknown()).describe("Platform-specific credentials. Fields vary by data source type."),displayName:w.string().optional().describe("Optional human-readable name for this connection.")}),kY=w.object({connectionId:w.string().uuid().describe("ID of the created connection."),publicKey:w.string().describe("Auto-generated public API key for this connection. Store this securely — it is only shown once.")}),j4=T({operationId:"dataSources.createConnection",description:"Create a new data source connection. Validates credentials, encrypts sensitive fields, and auto-generates a public API key.",backend:"api",route:{method:"POST",path:"/data-sources/connections",successStatus:201,tags:["Data Sources"]},input:qY,output:kY,pagination:"none",async:"sync"}),HY=w.object({connectionId:w.string().uuid().describe("Connection ID to list streams for.")}),FY=w.object({streams:w.array(E9)}),_U=T({operationId:"dataSources.listStreams",description:"List streams for a data source connection.",backend:"api",route:{method:"GET",path:"/data-sources/connections/{connectionId}/streams",tags:["Data Sources"]},input:HY,output:FY,pagination:"none",async:"sync"}),bY=w.object({connectionId:w.string().uuid().describe("Connection ID to create the stream under."),displayName:w.string().describe("Resource name, e.g. service or app name."),config:w.record(w.string(),w.unknown()).describe("Platform-specific stream configuration.")}),gY=w.object({streamId:w.string().uuid().describe("ID of the created stream.")}),UU=T({operationId:"dataSources.createStream",description:"Create a new stream for a data source connection. Triggers async provisioning.",backend:"api",route:{method:"POST",path:"/data-sources/connections/{connectionId}/streams",successStatus:201,tags:["Data Sources"]},input:bY,output:gY,pagination:"none",async:"sync"}),SY=w.object({streamId:w.string().uuid().describe("Stream ID to fetch.")}),BY=w.object({stream:E9}),DU=T({operationId:"dataSources.getStream",description:"Get one data source stream by ID. Use to poll provisioning status.",backend:"api",route:{method:"GET",path:"/data-sources/streams/{streamId}",tags:["Data Sources"]},input:SY,output:BY,pagination:"none",async:"sync"}),DL={listTypes:$U.contract,listConnections:A4.contract,getConnection:vU.contract,createConnection:j4.contract,listStreams:_U.contract,createStream:UU.contract,getStream:DU.contract}});var IU,ZY,GU,JU,MY,TY,zY,AY,R9,C9,jY,EY,xY,RY,CY,u9,uY,yY,fY,cY,hY,E4,x4,R4,C4,u4,wU,XU,QU,YU,PU,IL,GL;var y9=L(()=>{k$();S$();IU=/^[a-zA-Z0-9\s\-_]+$/,ZY=w.object({id:w.string().uuid(),name:w.string(),expiresAt:w.string().datetime().nullable(),lastUsedAt:w.string().datetime().nullable(),createdAt:w.string().datetime()}),GU=ZY.extend({projectId:w.string().uuid(),dataSourceConnectionId:w.string().uuid().nullable().describe("Linked data source connection ID when this key is scoped to one data source.")}),JU=ZY.extend({projectId:w.string().uuid().nullable()}),MY=w.object({projectId:w.string().uuid().optional().describe("Project to list keys for. Auto-filled from CLI and SDK context when omitted."),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of keys to return per page."),cursor:w.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),TY=w.object({publicKeys:w.array(GU),nextCursor:w.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),zY=w.object({secretKeys:w.array(JU),nextCursor:w.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),AY=w.object({projectId:w.string().uuid().optional().describe("Project containing the key. Auto-filled from CLI and SDK context when omitted."),keyId:w.string().uuid().describe("Key ID to fetch.")}),R9=w.object({publicKey:GU}),C9=w.object({secretKey:JU}),jY=w.object({projectId:w.string().uuid().optional().describe("Project to create the key in. Auto-filled from CLI and SDK context when omitted."),name:w.string().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(IU,"Name can only contain letters, numbers, spaces, hyphens, and underscores").describe("Human-readable name for the key."),expiresAt:w.string().datetime().optional().describe("Optional expiration timestamp for the key.")}),EY=w.object({publicKey:GU.extend({value:w.string()})}),xY=w.object({secretKey:JU.extend({value:w.string()})}),RY=w.object({projectId:w.string().uuid().optional().describe("Project containing the key. Auto-filled from CLI and SDK context when omitted."),keyId:w.string().uuid().describe("Key ID to update."),name:w.string().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(IU,"Name can only contain letters, numbers, spaces, hyphens, and underscores").optional().describe("New human-readable name for the key."),expiresAt:w.string().datetime().nullable().optional().describe("New expiration timestamp for the key, or null to clear it.")}),CY=w.object({params:w.object({keyId:w.string().uuid().describe("Key ID to delete.")}),query:w.object({projectId:w.string().uuid().optional().describe("Project containing the key. Auto-filled from CLI and SDK context when omitted.")})}).transform(({params:$,query:v})=>({...v,...$})),u9=w.object({}),uY=w.object({limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of keys to return per page."),cursor:w.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),yY=w.object({keyId:w.string().uuid().describe("Key ID to fetch.")}),fY=w.object({projectId:w.string().uuid().optional().describe("Project to scope this key to. When set, the key can only access resources within this project. Omit for organization-wide access."),name:w.string().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(IU,"Name can only contain letters, numbers, spaces, hyphens, and underscores").describe("Human-readable name for the key."),expiresAt:w.string().datetime().optional().describe("Optional expiration timestamp for the key.")}),cY=w.object({keyId:w.string().uuid().describe("Key ID to update."),name:w.string().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(IU,"Name can only contain letters, numbers, spaces, hyphens, and underscores").optional().describe("New human-readable name for the key."),expiresAt:w.string().datetime().nullable().optional().describe("New expiration timestamp for the key, or null to clear it.")}),hY=w.object({params:w.object({keyId:w.string().uuid().describe("Key ID to delete.")})}).transform(({params:$})=>({...$})),E4=T({operationId:"publicKeys.list",description:"List public keys within one project.",backend:"api",route:{method:"GET",path:"/public-keys",tags:["Public Keys"]},input:MY,output:TY,pagination:"cursor",async:"sync",examples:[{name:"list-public-keys",input:{projectId:"11111111-1111-4111-8111-111111111111",limit:25},output:{publicKeys:[{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",name:"CLI forwarder",dataSourceConnectionId:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}],nextCursor:null}}]}),x4=T({operationId:"publicKeys.get",description:"Get one public key within one project.",backend:"api",route:{method:"GET",path:"/public-keys/{keyId}",tags:["Public Keys"]},input:AY,output:R9,pagination:"none",async:"sync",examples:[{name:"get-public-key",input:{projectId:"11111111-1111-4111-8111-111111111111",keyId:"22222222-2222-4222-8222-222222222222"},output:{publicKey:{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",name:"CLI forwarder",dataSourceConnectionId:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}}}]}),R4=T({operationId:"publicKeys.create",description:"Create one public key within one project.",backend:"api",route:{method:"POST",path:"/public-keys",successStatus:201,tags:["Public Keys"]},input:jY,output:EY,pagination:"none",async:"sync",examples:[{name:"create-public-key",input:{projectId:"11111111-1111-4111-8111-111111111111",name:"CLI forwarder"},output:{publicKey:{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",name:"CLI forwarder",dataSourceConnectionId:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z",value:"sazabi_public_example"}}}]}),C4=T({operationId:"publicKeys.update",description:"Update one public key within one project.",backend:"api",route:{method:"PATCH",path:"/public-keys/{keyId}",tags:["Public Keys"]},input:RY,output:R9,pagination:"none",async:"sync",examples:[{name:"rename-public-key",input:{projectId:"11111111-1111-4111-8111-111111111111",keyId:"22222222-2222-4222-8222-222222222222",name:"Updated CLI forwarder"},output:{publicKey:{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",name:"Updated CLI forwarder",dataSourceConnectionId:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}}}]}),u4=T({operationId:"publicKeys.delete",description:"Delete one public key within one project.",backend:"api",route:{method:"DELETE",path:"/public-keys/{keyId}",successStatus:204,tags:["Public Keys"],inputStructure:"detailed"},input:CY,output:u9,pagination:"none",async:"sync"}),wU=T({operationId:"secretKeys.list",description:"List secret keys within the organization.",backend:"api",route:{method:"GET",path:"/secret-keys",tags:["Secret Keys"]},input:uY,output:zY,pagination:"cursor",async:"sync",examples:[{name:"list-secret-keys",input:{limit:25},output:{secretKeys:[{id:"33333333-3333-4333-8333-333333333333",projectId:null,name:"CI agent",expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}],nextCursor:null}}]}),XU=T({operationId:"secretKeys.get",description:"Get one secret key within the organization.",backend:"api",route:{method:"GET",path:"/secret-keys/{keyId}",tags:["Secret Keys"]},input:yY,output:C9,pagination:"none",async:"sync",examples:[{name:"get-secret-key",input:{keyId:"33333333-3333-4333-8333-333333333333"},output:{secretKey:{id:"33333333-3333-4333-8333-333333333333",projectId:null,name:"CI agent",expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}}}]}),QU=T({operationId:"secretKeys.create",description:"Create one secret key within the organization.",backend:"api",route:{method:"POST",path:"/secret-keys",successStatus:201,tags:["Secret Keys"]},input:fY,output:xY,pagination:"none",async:"sync",examples:[{name:"create-secret-key",input:{name:"CI agent"},output:{secretKey:{id:"33333333-3333-4333-8333-333333333333",projectId:null,name:"CI agent",expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z",value:"sazabi_secret_example"}}}]}),YU=T({operationId:"secretKeys.update",description:"Update one secret key within the organization.",backend:"api",route:{method:"PATCH",path:"/secret-keys/{keyId}",tags:["Secret Keys"]},input:cY,output:C9,pagination:"none",async:"sync",examples:[{name:"rename-secret-key",input:{keyId:"33333333-3333-4333-8333-333333333333",name:"Updated CI agent"},output:{secretKey:{id:"33333333-3333-4333-8333-333333333333",projectId:null,name:"Updated CI agent",expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}}}]}),PU=T({operationId:"secretKeys.delete",description:"Delete one secret key within the organization.",backend:"api",route:{method:"DELETE",path:"/secret-keys/{keyId}",successStatus:204,tags:["Secret Keys"],inputStructure:"detailed"},input:hY,output:u9,pagination:"none",async:"sync"}),IL={list:E4.contract,get:x4.contract,create:R4.contract,update:C4.contract,delete:u4.contract},GL={list:wU.contract,get:XU.contract,create:QU.contract,update:YU.contract,delete:PU.contract}});var rY,mY,lY,iY,nY,dY,oY,JL,tY,pY,y4,wL;var f9=L(()=>{k$();S$();rY=w.enum(["eq","neq","in","contains","starts_with","gt","gte","lt","lte","between","exists"]).describe("Filter operator: 'eq' (equals), 'neq' (not equals), 'in' (in array), 'contains' (substring), 'starts_with' (prefix), 'gt' (greater than), 'gte' (greater than or equal), 'lt' (less than), 'lte' (less than or equal), 'between' (range), 'exists' (field exists)"),mY=w.enum(["any","all","phrase"]).describe("Search mode: 'any' (match any token), 'all' (match all tokens), 'phrase' (exact phrase match)"),lY=w.object({query:w.string().min(1,"Search query must be at least 1 character").max(500,"Search query must be at most 500 characters").describe("Search query text (1-500 characters)"),fields:w.array(w.string()).optional().describe("Fields to search in (defaults to backend allowlist)"),mode:mY.optional().default("all").describe("Token matching mode")}),iY=w.object({field:w.string().describe("Field name to filter on"),op:rY.describe("Filter operator"),value:w.union([w.string(),w.number(),w.boolean(),w.array(w.union([w.string(),w.number()])),w.object({from:w.string(),to:w.string()})]).describe("Filter value (type depends on operator)")}).superRefine(($,v)=>{if($.op==="in"&&!Array.isArray($.value))v.addIssue({code:w.ZodIssueCode.custom,message:"Value must be an array when op is 'in'",path:["value"]});if($.op==="between"){let U=$.value;if(!(typeof U==="object"&&U!==null&&("from"in U)&&("to"in U)))v.addIssue({code:w.ZodIssueCode.custom,message:"Value must be an object with from/to when op is 'between'",path:["value"]})}if($.op==="exists"&&typeof $.value!=="boolean")v.addIssue({code:w.ZodIssueCode.custom,message:"Value must be boolean when op is 'exists'",path:["value"]})}),nY=w.object({field:w.string().describe("Field name to sort by"),direction:w.enum(["asc","desc"]).default("desc").describe("Sort direction: 'asc' for ascending, 'desc' for descending")}),dY=w.object({limit:w.number().int().min(1,"Limit must be at least 1").max(1000,"Limit must be at most 1000").default(50).describe("Maximum number of rows to return"),cursor:w.string().optional().describe("Opaque cursor from previous response for pagination")}),oY=w.object({projectId:w.string().uuid().optional().describe("Project to query logs for. Auto-filled from CLI and SDK context when omitted."),search:lY.optional().describe("Full-text search configuration"),filters:w.array(iY).optional().describe("Structured filter clauses (ANDed together)"),select:w.array(w.string()).optional().describe("Fields to return (defaults to backend default set)"),sort:nY.optional().describe("Sort configuration (defaults to timestamp desc)"),pagination:dY.optional().describe("Pagination configuration")}),JL=w.object({cursor:w.string().nullable().describe("Cursor for next page (null if no more results)"),hasMore:w.boolean().describe("Whether more results are available")}),tY=w.object({count:w.number().int().nonnegative().describe("Number of log rows returned in this response"),took:w.number().nonnegative().describe("Query execution time in milliseconds")}),pY=w.object({data:w.array(w.record(w.string(),w.any())).describe("Array of log rows with selected fields"),nextCursor:w.string().nullable().describe("Pass as 'cursor' in the next query to fetch the next page. Null when there are no more results."),meta:tY.describe("Query execution metadata")}),y4=T({operationId:"logs.query",description:"Query logs within one project via the platform API proxy.",backend:"api",route:{method:"POST",path:"/logs/query",tags:["Logs"]},input:oY,output:pY,pagination:"cursor",async:"sync"}),wL={query:y4.contract}});var nv,aY,eY,sY,$P,vP,_P,UP,KU,XL;var t6=L(()=>{k$();S$();nv=w.enum(["admin","member"]),aY=w.object({id:w.string().min(1),name:w.string(),slug:w.string(),logo:w.string().nullable().optional(),role:nv}),eY=w.object({id:w.string().min(1),name:w.string().nullable(),email:w.string().email()}),sY=w.object({credentialType:w.literal("user"),user:eY,activeOrganizationId:w.string().min(1).nullable(),organizations:w.array(aY).describe("Organizations the user belongs to, including membership role.")}),$P=w.object({credentialType:w.literal("secret"),organization:w.object({id:w.string().min(1),name:w.string(),slug:w.string(),logo:w.string().nullable().optional()}),keyName:w.string()}),vP=w.object({credentialType:w.literal("partner"),superorganization:w.object({id:w.string().uuid(),name:w.string()})}),_P=w.object({}),UP=w.discriminatedUnion("credentialType",[sY,$P,vP]),KU=T({operationId:"me.get",description:"Return the identity and available context for the current credential.",backend:"api",route:{method:"GET",path:"/me",tags:["Auth"]},input:_P,output:UP,pagination:"none",async:"sync"}),XL=KU.contract});var c9,DP,IP,GP,JP,wP,XP,VU,OU,WU,QL;var h9=L(()=>{k$();S$();t6();c9=w.object({membershipId:w.string().min(1).describe("Organization membership record ID."),userId:w.string().min(1).describe("User ID for the organization member."),name:w.string().nullable().describe("Display name for the member, when available."),email:w.string().email().describe("Email address for the member."),imageUrl:w.string().nullable().describe("Profile image URL for the member, when available."),role:nv.describe("Organization role."),createdAt:w.string().datetime().describe("When the membership was created.")}),DP=w.object({organizationId:w.string().min(1).optional().describe("Organization to list members for. Auto-filled from CLI and SDK context when omitted.")}),IP=w.object({members:w.array(c9).describe("Members visible within the selected organization.")}),GP=w.object({organizationId:w.string().min(1).optional().describe("Organization containing the member. Auto-filled from CLI and SDK context when omitted."),userId:w.string().min(1).describe("User ID of the member to update."),role:nv.describe("Role to assign.")}),JP=w.object({member:c9.describe("Updated organization member.")}),wP=w.object({params:w.object({userId:w.string().min(1).describe("User ID of the member to remove.")}),query:w.object({organizationId:w.string().min(1).optional().describe("Organization containing the member. Auto-filled from CLI and SDK context when omitted.")})}).transform(({params:$,query:v})=>({...v,...$})),XP=w.object({removedUserId:w.string().min(1).describe("User ID removed from the organization.")}),VU=T({operationId:"members.list",description:"List members in an organization.",backend:"api",route:{method:"GET",path:"/members",tags:["Members"]},input:DP,output:IP,pagination:"none",async:"sync",examples:[{name:"organization-members",input:{organizationId:"organization-123"},output:{members:[{membershipId:"membership-123",userId:"user-123",name:"Alex Admin",email:"alex@example.com",imageUrl:null,role:"admin",createdAt:"2026-01-01T00:00:00.000Z"}]}}]}),OU=T({operationId:"members.updateRole",description:"Update a member's organization role.",backend:"api",route:{method:"PATCH",path:"/members/{userId}/role",tags:["Members"]},input:GP,output:JP,pagination:"none",async:"sync",examples:[{name:"promote-member",input:{organizationId:"organization-123",userId:"user-456",role:"admin"},output:{member:{membershipId:"membership-456",userId:"user-456",name:"Mina Member",email:"mina@example.com",imageUrl:null,role:"admin",createdAt:"2026-01-01T00:00:00.000Z"}}}]}),WU=T({operationId:"members.remove",description:"Remove a member from an organization.",backend:"api",route:{method:"DELETE",path:"/members/{userId}",tags:["Members"],inputStructure:"detailed"},input:wP,output:XP,pagination:"none",async:"sync"}),QL={list:VU.contract,updateRole:OU.contract,remove:WU.contract}});var QP,r9,YP,PP,KP,VP,OP,f4,WP,LU,NU,qU,YL;var p6=L(()=>{k$();S$();QP=w.enum(["processing","completed","aborted","error"]),r9=w.object({id:w.string().uuid(),threadId:w.string().uuid(),userMessageId:w.string().uuid().nullable(),assistantMessageId:w.string().uuid().nullable(),parentRunId:w.string().uuid().nullable(),workflowRunId:w.string().nullable(),status:QP,source:w.enum(["web","api","mcp","slack","agent","cli"]),createdAt:w.string().datetime(),updatedAt:w.string().datetime(),completedAt:w.string().datetime().nullable()}),YP=w.object({projectId:w.string().uuid().optional().describe("Project ID to list runs for. Auto-filled from CLI and SDK context when omitted."),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of runs to return per page."),cursor:w.string().datetime().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),PP=w.object({runs:w.array(r9),nextCursor:w.string().datetime().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),KP=w.object({threadId:w.string().uuid().describe("Thread ID to list runs for."),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of runs to return per page."),cursor:w.string().datetime().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),VP=w.object({runs:w.array(r9),nextCursor:w.string().datetime().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),OP=w.object({runId:w.string().uuid().describe("Run ID returned by a deferred operation.")}),f4=w.object({completed:w.boolean().describe("Whether the run has reached a terminal status."),threadId:w.string().uuid().describe("Thread ID associated with the run."),runId:w.string().uuid().describe("Run ID for subsequent polling."),status:QP.describe("Current run lifecycle status."),response:w.string().nullable().describe("Assistant response text when the run has completed.")}),WP=f4.describe("Current run state and, when complete, the assistant response."),LU=T({operationId:"runs.list",description:"List deferred runs within one project.",backend:"api",route:{method:"GET",path:"/runs",tags:["Runs"]},input:YP,output:PP,pagination:"cursor",async:"sync"}),NU=T({operationId:"runs.listForThread",description:"List deferred runs for one thread.",backend:"api",route:{method:"GET",path:"/threads/{threadId}/runs",tags:["Runs"]},input:KP,output:VP,pagination:"cursor",async:"sync"}),qU=T({operationId:"runs.get",description:"Get the current result for a deferred run by run ID.",backend:"api",route:{method:"GET",path:"/runs/{runId}",tags:["Runs"]},input:OP,output:WP,pagination:"none",async:"sync",examples:[{name:"processing-run",input:{runId:"33333333-3333-4333-8333-333333333333"},output:{completed:!1,threadId:"22222222-2222-4222-8222-222222222222",runId:"33333333-3333-4333-8333-333333333333",status:"processing",response:null}}]}),YL={list:LU.contract,listForThread:NU.contract,get:qU.contract}});var kU,PL,KL,VL,OL,WL,LL,NL,qL,HU,LP,NP,qP,kP,HP,FP,bP,gP,SP,BP,FU,bU,gU,SU,BU,kL;var ZU=L(()=>{k$();S$();p6();kU=w.object({id:w.string().uuid(),projectId:w.string().uuid(),title:w.string().nullable(),status:w.enum(["regular","archived"]),createdAt:w.string().datetime(),updatedAt:w.string().datetime()}),PL=w.object({type:w.literal("message"),message:w.string()}),KL=w.object({type:w.literal("reasoning"),reasoning:w.string(),status:w.enum(["in_progress","complete"]).optional()}),VL=w.object({type:w.literal("tool_call"),name:w.string(),params:w.any().optional(),result:w.any().optional(),status:w.enum(["in_progress","success","error","unknown"]).optional(),toolCallId:w.string().optional(),durationMs:w.number().nonnegative().optional()}),OL=w.object({type:w.literal("artifact"),name:w.enum(["timeseries","table","log_detail","integration_required","alert_card"]),data:w.any(),toolCallId:w.string().optional()}),WL=w.object({type:w.literal("fork"),sourceThreadId:w.string(),sourceMessageId:w.string(),sourceThreadTitle:w.string().nullable()}),LL=w.object({type:w.literal("summary"),summary:w.string()}),NL=w.object({type:w.literal("slack_context"),channelId:w.string(),isTruncated:w.boolean().optional(),messages:w.array(w.object({timestamp:w.string(),slackUserId:w.string().optional(),displayName:w.string(),text:w.string(),isBot:w.boolean(),files:w.array(w.object({name:w.string(),mimetype:w.string(),size:w.number().optional(),attachmentId:w.string().uuid().optional(),ingestionStatus:w.enum(["attached","unsupported","oversized","skipped","unavailable"]).optional()})).optional()}))}),qL=w.union([PL,KL,VL,OL,WL,LL,NL]),HU=w.object({id:w.string().uuid(),role:w.enum(["user","assistant"]),content:w.array(qL),createdAt:w.string().datetime()}),LP=w.object({projectId:w.string().uuid().optional().describe("Project to list threads for. Auto-filled from CLI and SDK context when omitted."),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of threads to return per page."),cursor:w.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page."),status:w.enum(["regular","archived"]).optional().describe("Filter by thread status. 'regular' returns active threads, 'archived' returns archived threads.")}),NP=w.object({threads:w.array(kU).describe("The page of threads matching the query."),nextCursor:w.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),qP=w.object({threadId:w.string().uuid().describe("Thread ID returned by threads.list or threads.create.")}),kP=w.object({thread:kU.describe("The requested thread."),messages:w.array(HU).describe("Messages currently stored on the thread in chronological order.")}),HP=w.object({projectId:w.string().uuid().optional().describe("Project to create the thread in. Auto-filled from CLI and SDK context when omitted."),message:w.string().min(1,"Message cannot be empty").max(1e4,"Message cannot exceed 10000 characters").describe("Initial user message that starts the thread."),wait:w.boolean().default(!0).describe("Whether the server should wait for the agent run before responding."),timeoutSeconds:w.coerce.number().int().min(1).max(20).default(20).describe("Maximum seconds to wait when wait is true before handing off to polling.")}),FP=f4.describe("Deferred run result for creating a thread."),bP=w.object({threadId:w.string().uuid().describe("Thread ID whose current processing status should be returned.")}),gP=w.object({status:w.enum(["idle","processing"]),lastRunStatus:w.enum(["error"]).nullable()}),SP=w.object({threadId:w.string().uuid().describe("Thread ID of the thread to update."),status:w.enum(["regular","archived"]).describe("New status for the thread. 'archived' hides the thread from the sidebar.")}),BP=w.object({thread:kU.describe("The updated thread.")}),FU=T({operationId:"threads.list",description:"List threads in a project, optionally filtered by status.",backend:"api",route:{method:"GET",path:"/threads",tags:["Threads"]},input:LP,output:NP,pagination:"cursor",async:"sync",examples:[{name:"active-threads",input:{projectId:"11111111-1111-4111-8111-111111111111",status:"regular",limit:10},output:{threads:[{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",title:"API returning 500s",status:"regular",createdAt:"2026-01-01T00:00:00.000Z",updatedAt:"2026-01-01T00:05:00.000Z"}],nextCursor:null}}]}),bU=T({operationId:"threads.get",description:"Get a thread and its messages.",backend:"api",route:{method:"GET",path:"/threads/{threadId}",tags:["Threads"]},input:qP,output:kP,pagination:"none",async:"sync"}),gU=T({operationId:"threads.getStatus",description:"Get the current processing status for a thread.",backend:"api",route:{method:"GET",path:"/threads/{threadId}/status",tags:["Threads"]},input:bP,output:gP,pagination:"none",async:"sync",examples:[{name:"processing-thread",input:{threadId:"22222222-2222-4222-8222-222222222222"},output:{status:"processing",lastRunStatus:null}}]}),SU=T({operationId:"threads.create",description:"Create a thread with an initial message and optionally wait for the agent response.",backend:"api",route:{method:"POST",path:"/threads",tags:["Threads"],successStatus:201},input:HP,output:FP,pagination:"none",async:"deferred",examples:[{name:"async-handoff",input:{projectId:"11111111-1111-4111-8111-111111111111",message:"Investigate elevated 500s in production.",wait:!1,timeoutSeconds:20},output:{completed:!1,threadId:"22222222-2222-4222-8222-222222222222",runId:"33333333-3333-4333-8333-333333333333",status:"processing",response:null}}]}),BU=T({operationId:"threads.update",description:"Update a thread's status.",backend:"api",route:{method:"PATCH",path:"/threads/{threadId}",tags:["Threads"]},input:SP,output:BP,pagination:"none",async:"sync",examples:[{name:"archive-thread",input:{threadId:"22222222-2222-4222-8222-222222222222",status:"archived"},output:{thread:{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",title:"API returning 500s",status:"archived",createdAt:"2026-01-01T00:00:00.000Z",updatedAt:"2026-01-01T00:10:00.000Z"}}}]}),kL={list:FU.contract,get:bU.contract,getStatus:gU.contract,create:SU.contract,update:BU.contract}});var ZP,MP,TP,zP,m9,l9;var i9=L(()=>{k$();S$();p6();ZU();ZP=w.object({threadId:w.string().uuid().describe("Thread ID to list messages for."),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of messages to return per page."),cursor:w.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),MP=w.object({messages:w.array(HU),nextCursor:w.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),TP=w.object({threadId:w.string().uuid().describe("Thread ID to append the message to."),message:w.string().min(1,"Message cannot be empty").max(1e4,"Message cannot exceed 10000 characters"),wait:w.boolean().default(!0).describe("Whether the server should wait for the appended message run before responding."),timeoutSeconds:w.coerce.number().int().min(1).max(20).default(20).describe("Maximum seconds to wait when wait is true before handing off to polling.")}),zP=f4.describe("Deferred run result for appending a message to an existing thread."),m9=T({operationId:"messages.list",description:"List messages in a thread with cursor pagination.",backend:"api",route:{method:"GET",path:"/threads/{threadId}/messages",tags:["Messages"]},input:ZP,output:MP,pagination:"cursor",async:"sync",examples:[{name:"thread-messages",input:{threadId:"22222222-2222-4222-8222-222222222222",limit:2},output:{messages:[{id:"33333333-3333-4333-8333-333333333333",role:"user",content:[{type:"message",message:"What changed in the intake pipeline?"}],createdAt:"2026-01-01T00:00:00.000Z"}],nextCursor:null}}]}),l9=T({operationId:"messages.append",description:"Append a user message to an existing thread and trigger a deferred run.",backend:"api",route:{method:"POST",path:"/threads/{threadId}/messages",successStatus:201,tags:["Messages"]},input:TP,output:zP,pagination:"none",async:"deferred",examples:[{name:"append-processing",input:{threadId:"22222222-2222-4222-8222-222222222222",message:"Follow up on the intake backlog.",wait:!1,timeoutSeconds:20},output:{completed:!1,threadId:"22222222-2222-4222-8222-222222222222",runId:"33333333-3333-4333-8333-333333333333",status:"processing",response:null}}]})});var MU,AP,jP,EP,xP,RP,CP,uP,TU,zU,AU,HL;var n9=L(()=>{k$();S$();t6();MU=w.object({id:w.string().min(1),name:w.string(),slug:w.string(),logo:w.string().nullable().optional()}),AP=MU.extend({role:nv.optional()}),jP=w.object({}),EP=w.object({organizations:w.array(AP).describe("Organizations available to the current credential.")}),xP=w.object({organizationId:w.string().min(1).describe("Organization ID to fetch.")}),RP=w.object({organization:MU}),CP=w.object({organizationId:w.string().min(1).describe("Organization ID to update. SDK and CLI callers can auto-fill this before dispatch."),name:w.string().trim().min(1).max(100).describe("New organization name.")}),uP=w.object({organization:MU.describe("Updated organization.")}),TU=T({operationId:"organizations.list",description:"List organizations available to the current credential.",backend:"api",route:{method:"GET",path:"/organizations",tags:["Organizations"]},input:jP,output:EP,pagination:"none",async:"sync"}),zU=T({operationId:"organizations.get",description:"Get one organization by ID.",backend:"api",route:{method:"GET",path:"/organizations/{organizationId}",tags:["Organizations"]},input:xP,output:RP,pagination:"none",async:"sync"}),AU=T({operationId:"organizations.update",description:"Update one organization.",backend:"api",route:{method:"PATCH",path:"/organizations/{organizationId}",tags:["Organizations"]},input:CP,output:uP,pagination:"none",async:"sync",examples:[{name:"rename-organization",input:{organizationId:"organization-123",name:"Observed Platform"},output:{organization:{id:"organization-123",name:"Observed Platform",slug:"acme",logo:null}}}]}),HL={list:TU.contract,get:zU.contract,update:AU.contract}});var jU,d9,yP,fP,cP,hP,EU,xU,FL;var o9=L(()=>{k$();S$();jU=w.enum(["us-east-1","us-east-2","us-west-1","us-west-2","eu-central-1","eu-central-2","eu-north-1","eu-south-1","eu-south-2","eu-west-1","eu-west-2","eu-west-3"]),d9=w.object({id:w.string().uuid(),organizationId:w.string().min(1),name:w.string(),region:jU}),yP=w.object({organizationId:w.string().min(1).optional().describe("Organization to list projects for. Auto-filled from CLI and SDK context when omitted.")}),fP=w.object({projects:w.array(d9).describe("Projects visible within the selected organization.")}),cP=w.object({projectId:w.string().uuid().describe("Project ID to fetch.")}),hP=w.object({project:d9}),EU=T({operationId:"projects.list",description:"List projects in an organization.",backend:"api",route:{method:"GET",path:"/projects",tags:["Projects"]},input:yP,output:fP,pagination:"none",async:"sync"}),xU=T({operationId:"projects.get",description:"Get one project by ID.",backend:"api",route:{method:"GET",path:"/projects/{projectId}",tags:["Projects"]},input:cP,output:hP,pagination:"none",async:"sync"}),FL={list:EU.contract,get:xU.contract}});var t9,rP,mP,lP,iP,c4,h4,bL;var p9=L(()=>{k$();S$();t9=w.object({projectId:w.string().uuid().optional().describe("Project to search within. Auto-filled from CLI and SDK context when omitted."),query:w.string().trim().min(1,"Query must be at least 1 character").max(500,"Query must be at most 500 characters"),limit:w.coerce.number().min(1).max(100).default(20).describe("Maximum number of search results to return."),page:w.coerce.number().min(1).default(1).describe("One-based page number.")}),rP=t9.extend({status:w.enum(["regular","archived"]).optional().describe("Optional thread status filter.")}),mP=t9.extend({threadId:w.string().uuid().optional().describe("Optional thread restriction for message search."),role:w.enum(["user","assistant"]).optional().describe("Optional message role filter.")}),lP=w.object({threads:w.array(w.object({id:w.string().uuid(),projectId:w.string().uuid().optional(),title:w.string(),status:w.enum(["regular","archived"]),labels:w.array(w.string()),createdAt:w.string().datetime(),updatedAt:w.string().datetime(),highlights:w.array(w.string()),score:w.number().optional()})),pagination:w.object({page:w.number(),limit:w.number(),totalResults:w.number(),totalPages:w.number()}).describe("Page-based pagination metadata for the current search result.")}),iP=w.object({messages:w.array(w.object({id:w.string().uuid(),threadId:w.string().uuid(),threadTitle:w.string(),role:w.enum(["user","assistant"]),content:w.string(),createdAt:w.string().datetime(),updatedAt:w.string().datetime(),highlights:w.array(w.string()),score:w.number().optional()})),pagination:w.object({page:w.number(),limit:w.number(),totalResults:w.number(),totalPages:w.number()}).describe("Page-based pagination metadata for the current search result.")}),c4=T({operationId:"search.threads",description:"Search threads within one project.",backend:"api",route:{method:"GET",path:"/search/threads",tags:["Search"]},input:rP,output:lP,pagination:"page",async:"sync",examples:[{name:"search-open-incidents",input:{projectId:"11111111-1111-4111-8111-111111111111",query:"payment timeout",status:"regular",limit:10,page:1},output:{threads:[{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",title:"Payment timeout in us-west-2",status:"regular",labels:["payments","timeout"],createdAt:"2026-01-01T00:00:00.000Z",updatedAt:"2026-01-02T00:00:00.000Z",highlights:["payment timeout"],score:123.45}],pagination:{page:1,limit:10,totalResults:1,totalPages:1}}}]}),h4=T({operationId:"search.messages",description:"Search messages within one project.",backend:"api",route:{method:"GET",path:"/search/messages",tags:["Search"]},input:mP,output:iP,pagination:"page",async:"sync",examples:[{name:"search-assistant-messages",input:{projectId:"11111111-1111-4111-8111-111111111111",query:"rollback",role:"assistant",limit:10,page:1},output:{messages:[{id:"33333333-3333-4333-8333-333333333333",threadId:"22222222-2222-4222-8222-222222222222",threadTitle:"Deployment rollback guidance",role:"assistant",content:"Rollback the ingestion deployment and confirm queue depth.",createdAt:"2026-01-02T00:00:00.000Z",updatedAt:"2026-01-02T00:00:00.000Z",highlights:["Rollback the ingestion deployment"],score:98.76}],pagination:{page:1,limit:10,totalResults:1,totalPages:1}}}]}),bL={threads:c4.contract,messages:h4.contract}});var a9;var nP=L(()=>{x9();y9();f9();t6();h9();i9();n9();o9();p6();p9();ZU();a9={me:KU.contract,logs:{query:y4.contract},dataSources:{listTypes:$U.contract,listConnections:A4.contract,getConnection:vU.contract,createConnection:j4.contract,listStreams:_U.contract,createStream:UU.contract,getStream:DU.contract},organizations:{list:TU.contract,get:zU.contract,update:AU.contract},members:{list:VU.contract,updateRole:OU.contract,remove:WU.contract},publicKeys:{list:E4.contract,get:x4.contract,create:R4.contract,update:C4.contract,delete:u4.contract},secretKeys:{list:wU.contract,get:XU.contract,create:QU.contract,update:YU.contract,delete:PU.contract},projects:{list:EU.contract,get:xU.contract},search:{threads:c4.contract,messages:h4.contract},messages:{list:m9.contract,append:l9.contract},threads:{list:FU.contract,get:bU.contract,getStatus:gU.contract,create:SU.contract,update:BU.contract},runs:{list:LU.contract,listForThread:NU.contract,get:qU.contract}}});var r4,e9,dP,oP,a6,tP,pP,aP,eP,sP,$K,vK,_K,UK,DK,e6,IK,GK,JK,wK,XK,QK,YK,PK,KK,VK,s9,OK,WK,LK,NK,qK,kK,$w,HK,FK,bK,gK,SK,BK,ZK,MK,TK,zK,AK,jK,EK,xK,RK,CK,uK,yK,fK,cK,hK,rK,mK,gL;var lK=L(()=>{k$();S$();r4=/^[a-zA-Z0-9\s\-_]+$/,e9=w.enum(["us-west-2","us-east-1","eu-central-1"]),dP=w.object({id:w.string().uuid(),name:w.string(),createdAt:w.string().datetime()}),oP=w.object({superorganization:dP}),a6=w.object({id:w.string(),name:w.string(),createdAt:w.string().datetime()}),tP=w.object({limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of organizations to return per page."),cursor:w.string().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),pP=w.object({organizations:w.array(a6),nextCursor:w.string().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),aP=w.object({organizationId:w.string()}),eP=w.object({organization:a6}),sP=w.object({name:w.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(r4,"Name can only contain letters, numbers, spaces, hyphens, and underscores")}),$K=w.object({organization:a6}),vK=w.object({organizationId:w.string(),name:w.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(r4,"Name can only contain letters, numbers, spaces, hyphens, and underscores").optional()}),_K=w.object({organization:a6}),UK=w.object({params:w.object({organizationId:w.string()}),query:w.object({})}).transform(({params:$})=>$),DK=w.object({}),e6=w.object({id:w.string().uuid(),organizationId:w.string(),name:w.string(),region:e9,createdAt:w.string().datetime()}),IK=w.object({organizationId:w.string(),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of projects to return per page."),cursor:w.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),GK=w.object({projects:w.array(e6),nextCursor:w.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),JK=w.object({organizationId:w.string(),projectId:w.string().uuid().describe("Project ID to fetch.")}),wK=w.object({project:e6}),XK=w.object({organizationId:w.string(),name:w.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(r4,"Name can only contain letters, numbers, spaces, hyphens, and underscores"),region:e9.optional().default("us-west-2").describe("AWS region where the new project should be created.")}),QK=w.object({project:e6}),YK=w.object({organizationId:w.string(),projectId:w.string().uuid().describe("Project ID to update."),name:w.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(r4,"Name can only contain letters, numbers, spaces, hyphens, and underscores").optional()}),PK=w.object({project:e6}),KK=w.object({params:w.object({organizationId:w.string(),projectId:w.string().uuid().describe("Project ID to delete.")}),query:w.object({})}).transform(({params:$})=>$),VK=w.object({}),s9=w.object({id:w.string().uuid(),projectId:w.string().uuid().nullable(),name:w.string(),expiresAt:w.string().datetime().nullable(),lastUsedAt:w.string().datetime().nullable(),createdAt:w.string().datetime()}),OK=w.object({organizationId:w.string(),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of secret keys to return per page."),cursor:w.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),WK=w.object({secretKeys:w.array(s9),nextCursor:w.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),LK=w.object({organizationId:w.string(),name:w.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(r4,"Name can only contain letters, numbers, spaces, hyphens, and underscores"),expiresAt:w.string().datetime().optional(),projectId:w.string().uuid().optional().describe("Project to scope this key to. When set, the key can only access resources within this project.")}),NK=w.object({secretKey:s9.extend({value:w.string()})}),qK=w.object({params:w.object({organizationId:w.string(),keyId:w.string().uuid().describe("Secret key ID to delete.")}),query:w.object({})}).transform(({params:$})=>$),kK=w.object({}),$w=w.object({id:w.string().uuid(),projectId:w.string().uuid(),name:w.string(),expiresAt:w.string().datetime().nullable(),lastUsedAt:w.string().datetime().nullable(),createdAt:w.string().datetime()}),HK=w.object({organizationId:w.string(),projectId:w.string().uuid().describe("Project ID to list public keys for."),limit:w.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of public keys to return per page."),cursor:w.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),FK=w.object({publicKeys:w.array($w),nextCursor:w.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),bK=w.object({organizationId:w.string(),projectId:w.string().uuid().describe("Project ID where the key should be created."),name:w.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(r4,"Name can only contain letters, numbers, spaces, hyphens, and underscores"),expiresAt:w.string().datetime().optional()}),gK=w.object({publicKey:$w.extend({value:w.string()})}),SK=w.object({params:w.object({organizationId:w.string(),projectId:w.string().uuid().describe("Project ID that owns the key."),keyId:w.string().uuid().describe("Public key ID to delete.")}),query:w.object({})}).transform(({params:$})=>$),BK=w.object({}),ZK=T({operationId:"partner.superorganization.get",description:"Get the authenticated partner superorganization.",backend:"partner",route:{method:"GET",path:"/superorganization",tags:["Partner - Superorganization"]},input:w.object({}),output:oP,pagination:"none",async:"sync"}),MK=T({operationId:"partner.organizations.list",description:"List organizations under the authenticated superorganization.",backend:"partner",route:{method:"GET",path:"/organizations",tags:["Partner - Organizations"]},input:tP,output:pP,pagination:"cursor",async:"sync"}),TK=T({operationId:"partner.organizations.get",description:"Get one organization under the authenticated superorganization.",backend:"partner",route:{method:"GET",path:"/organizations/{organizationId}",tags:["Partner - Organizations"]},input:aP,output:eP,pagination:"none",async:"sync"}),zK=T({operationId:"partner.organizations.create",description:"Create one organization under the authenticated superorganization.",backend:"partner",route:{method:"POST",path:"/organizations",tags:["Partner - Organizations"],successStatus:201},input:sP,output:$K,pagination:"none",async:"sync"}),AK=T({operationId:"partner.organizations.update",description:"Update one organization under the authenticated superorganization.",backend:"partner",route:{method:"PATCH",path:"/organizations/{organizationId}",tags:["Partner - Organizations"]},input:vK,output:_K,pagination:"none",async:"sync"}),jK=T({operationId:"partner.organizations.delete",description:"Delete one organization under the authenticated superorganization.",backend:"partner",route:{method:"DELETE",path:"/organizations/{organizationId}",tags:["Partner - Organizations"],successStatus:204,inputStructure:"detailed"},input:UK,output:DK,pagination:"none",async:"sync"}),EK=T({operationId:"partner.projects.list",description:"List projects under one partner-managed organization.",backend:"partner",route:{method:"GET",path:"/organizations/{organizationId}/projects",tags:["Partner - Projects"]},input:IK,output:GK,pagination:"cursor",async:"sync"}),xK=T({operationId:"partner.projects.get",description:"Get one project under one partner-managed organization.",backend:"partner",route:{method:"GET",path:"/organizations/{organizationId}/projects/{projectId}",tags:["Partner - Projects"]},input:JK,output:wK,pagination:"none",async:"sync"}),RK=T({operationId:"partner.projects.create",description:"Create one project under one partner-managed organization.",backend:"partner",route:{method:"POST",path:"/organizations/{organizationId}/projects",tags:["Partner - Projects"],successStatus:201},input:XK,output:QK,pagination:"none",async:"sync"}),CK=T({operationId:"partner.projects.update",description:"Update one project under one partner-managed organization.",backend:"partner",route:{method:"PATCH",path:"/organizations/{organizationId}/projects/{projectId}",tags:["Partner - Projects"]},input:YK,output:PK,pagination:"none",async:"sync"}),uK=T({operationId:"partner.projects.delete",description:"Delete one project under one partner-managed organization.",backend:"partner",route:{method:"DELETE",path:"/organizations/{organizationId}/projects/{projectId}",tags:["Partner - Projects"],successStatus:204,inputStructure:"detailed"},input:KK,output:VK,pagination:"none",async:"sync"}),yK=T({operationId:"partner.secretKeys.list",description:"List secret keys under one partner-managed organization.",backend:"partner",route:{method:"GET",path:"/organizations/{organizationId}/secret-keys",tags:["Partner - Secret Keys"]},input:OK,output:WK,pagination:"cursor",async:"sync"}),fK=T({operationId:"partner.secretKeys.create",description:"Create one secret key under one partner-managed organization.",backend:"partner",route:{method:"POST",path:"/organizations/{organizationId}/secret-keys",tags:["Partner - Secret Keys"],successStatus:201},input:LK,output:NK,pagination:"none",async:"sync"}),cK=T({operationId:"partner.secretKeys.delete",description:"Delete one secret key under one partner-managed organization.",backend:"partner",route:{method:"DELETE",path:"/organizations/{organizationId}/secret-keys/{keyId}",tags:["Partner - Secret Keys"],successStatus:204,inputStructure:"detailed"},input:qK,output:kK,pagination:"none",async:"sync"}),hK=T({operationId:"partner.publicKeys.list",description:"List public keys under one partner-managed project.",backend:"partner",route:{method:"GET",path:"/organizations/{organizationId}/projects/{projectId}/public-keys",tags:["Partner - Public Keys"]},input:HK,output:FK,pagination:"cursor",async:"sync"}),rK=T({operationId:"partner.publicKeys.create",description:"Create one public key under one partner-managed project.",backend:"partner",route:{method:"POST",path:"/organizations/{organizationId}/projects/{projectId}/public-keys",tags:["Partner - Public Keys"],successStatus:201},input:bK,output:gK,pagination:"none",async:"sync"}),mK=T({operationId:"partner.publicKeys.delete",description:"Delete one public key under one partner-managed project.",backend:"partner",route:{method:"DELETE",path:"/organizations/{organizationId}/projects/{projectId}/public-keys/{keyId}",tags:["Partner - Public Keys"],successStatus:204,inputStructure:"detailed"},input:SK,output:BK,pagination:"none",async:"sync"}),gL={superorganization:{get:ZK.contract},organizations:{list:MK.contract,get:TK.contract,create:zK.contract,update:AK.contract,delete:jK.contract},projects:{list:EK.contract,get:xK.contract,create:RK.contract,update:CK.contract,delete:uK.contract},keys:{secretKeys:{list:yK.contract,create:fK.contract,delete:cK.contract},publicKeys:{list:hK.contract,create:rK.contract,delete:mK.contract}}}});var vw=L(()=>{nP();x9();S$();y9();f9();t6();h9();i9();n9();lK();o9();p6();p9();ZU()});var SL,yS,BL,RU=($)=>{return BL.includes($)};var _w=L(()=>{SL={"eu-central-1":"EU Central (Frankfurt)"},yS={"us-west-2":"US West","us-east-1":"US East","eu-central-1":SL["eu-central-1"]},BL=["us-west-2","us-east-1","eu-central-1"]});var Uw,Dw,Iw,iK;var nK=L(()=>{k$();Uw=w.object({severities:w.array(w.string()).optional().describe("Limit results to the listed severities."),services:w.array(w.string()).optional().describe("Limit results to the listed service names."),environments:w.array(w.string()).optional().describe("Limit results to the listed deployment environments."),searchTerm:w.string().optional().describe("Case-insensitive substring match against the log body."),traceId:w.string().optional().describe("Limit results to one trace ID.")}),Dw=w.object({service:w.string(),namespace:w.string(),environment:w.string(),host:w.string(),container:w.string(),pod:w.string()}),Iw=w.object({id:w.string(),timestamp:w.string().datetime(),severity:w.string(),body:w.string(),service:w.string(),traceId:w.string(),spanId:w.string(),attributes:w.record(w.string(),w.string()),resource:Dw}),iK=w.object({type:w.literal("logs"),timestamp:w.string().datetime(),data:w.array(Iw)})});var ZL="https://{region}.intake.sazabi.com",ML="wss://{region}.tail.sazabi.com",TL=3,oK=500,tK="sazabi.public_key",zL=($)=>{return $.startsWith("[")&&$.endsWith("]")?$.slice(1,-1):$},pK=($)=>{let v=zL($);return v==="localhost"||v==="127.0.0.1"||v==="::1"},AL,jL,EL,aK=($)=>{let v=new Map;return{tail:async(U)=>{let D=await hL($.credentialProvider,U.projectId,"logs.tail"),_=await rL($,v,D,U.region,"logs.tail"),I=xL({projectId:D,region:_,filters:U.filters,tailBaseUrl:$.tailBaseUrl}),G=await $.credentialProvider.getToken(),J=$.webSocket??globalThis.WebSocket;if(!J)throw Error("WebSocket transport is not available in this runtime.");return iL({token:G,url:I,signal:U.signal,webSocket:J})},forward:async(U)=>{let D=await mL($,v,U.projectId??await $.credentialProvider.getProjectId?.(),U.region,"logs.forward"),_=uL(D,$.intakeBaseUrl),I=$.fetch??globalThis.fetch,G=fL(U.logs,U.publicKey),J=tL(G);return await oL(I,_,G),{forwardedCount:J,failedCount:0}}}},xL=($)=>{let v=($.tailBaseUrl??ML).replace("{region}",$.region),U=RL(v)??new URL(v);U.searchParams.set("projectId",$.projectId);let D=CL($.filters);if(D)U.searchParams.set("filters",D);return U.toString()},RL=($)=>{let v=(()=>{try{return new URL($)}catch{return null}})();if(!v)return;if(!pK(v.hostname))return;return v.protocol="ws:",v.pathname="/tail",v},CL=($)=>{if(!$)return;let v=Object.entries($).filter(([,U])=>U!==void 0&&(!Array.isArray(U)||U.length>0)&&U!=="");if(v.length===0)return;return JSON.stringify(Object.fromEntries(v))},uL=($,v)=>{let U=(v??ZL).replace("{region}",$),D=U.endsWith("/")?U.slice(0,-1):U,_=yL(D);if(_)return _;let I=D.match(/^https:\/\/([a-z0-9-]+)\.intake\.([a-z0-9.]+)$/);return`${I?`https://otlp.${I[1]}.intake.${I[2]}`:D}/v1/logs`},yL=($)=>{let v=(()=>{try{return new URL($)}catch{return null}})();if(!v)return;if(!pK(v.hostname))return;return v.pathname="/adapters/otlp",v.toString()},fL=($,v)=>{let U=$.resourceLogs;if(!U||U.length===0)return{...$,resourceLogs:[{resource:{attributes:[eK(v)]},scopeLogs:[]}]};return{...$,resourceLogs:U.map((D)=>({...D,resource:{...D.resource,attributes:cL(D.resource?.attributes,v)}}))}},cL=($,v)=>{return[...($??[]).filter((D)=>D?.key!==tK),eK(v)]},eK=($)=>({key:tK,value:{stringValue:$}}),hL=async($,v,U)=>{let D=v??await $.getProjectId?.();if(D)return D;throw $7(U,"Project ID is required",["projectId"])},rL=async($,v,U,D,_)=>{let I=D??await sK($,v,U);return lL(I,_)},mL=async($,v,U,D,_)=>{if(D)return D;if(!U)throw $7(_,"Project ID is required",["projectId"]);return sK($,v,U)},sK=async($,v,U)=>{let D=v.get(U);if(D)return D;let _=$.raw.projects.get({projectId:U}).then((I)=>I.project.region);v.set(U,_);try{return await _}catch(I){throw v.delete(U),I}},lL=($,v)=>{if(RU($))return $;throw new D$("BAD_REQUEST",{message:`Log tail is not supported for project region ${$}.`,data:{operationId:v,missingContext:[]}})},iL=async($)=>{let v=[],U=[],D=!1,_=!1,I,G=0,J,X=(O)=>{if(D)return;D=!0,I=O;while(U.length>0){let S=U.shift();if(S)S({value:void 0,done:!0})}},Q=(O)=>{let S=U.shift();if(S){S({value:O,done:!1});return}v.push(O)},Y=()=>{if(J&&J.readyState<J.CLOSING)J.close(1000,"Client closed stream")},P=async()=>{await new Promise((O,S)=>{let B=!1,h;try{h=new $.webSocket($.url,[$.token])}catch(p){S(p instanceof Error?p:Error("Failed to open WebSocket connection."));return}J=h,h.onopen=()=>{if(G=0,!B)B=!0,O()},h.onmessage=(p)=>{let X$=nL(p.data);for(let $$ of X$)Q($$)},h.onerror=()=>{if(!B)B=!0,S(Error("WebSocket connection failed. Check the close event for details."))},h.onclose=(p)=>{if(!B){B=!0,S(dK(p.code,p.reason));return}if(_||D){X();return}if(dL(p.code)&&G<TL){G+=1,globalThis.setTimeout(()=>{P().catch((X$)=>{X(X$ instanceof Error?X$:Error(String(X$)))})},oK*2**(G-1));return}X(dK(p.code,p.reason))}})};$.signal?.addEventListener("abort",()=>{_=!0,Y(),X()},{once:!0}),await P();let V={[Symbol.asyncIterator](){return V},next:async()=>{if(v.length>0)return{value:v.shift(),done:!1};if(D){if(I)throw I;return{value:void 0,done:!0}}return new Promise((O)=>{U.push(O)}).then((O)=>{if(O.done&&I)throw I;return O})},return:async()=>{return _=!0,Y(),X(),{value:void 0,done:!0}},throw:async(O)=>{throw _=!0,Y(),X(O instanceof Error?O:Error(String(O))),O}};return V},nL=($)=>{let v=(()=>{if(typeof $==="string")return $;if($ instanceof ArrayBuffer)return new TextDecoder().decode($);return null})();if(!v)return[];try{let U=iK.safeParse(JSON.parse(v));if(!U.success)return[];return U.data.data}catch{return[]}},dL=($)=>{return![1000,1001,1008,4001,4003,4004].includes($)},dK=($,v)=>{if(v)return Error(v);let U={1000:"Normal closure",1001:"Endpoint going away",1002:"Protocol error",1003:"Unsupported data",1006:"Connection closed abnormally (no close frame received)",1007:"Invalid payload data",1008:"Policy violation",1009:"Message too big",1010:"Missing extension",1011:"Internal server error",1015:"TLS handshake failure",4001:"Authentication failed - check your credential",4003:"Forbidden - credential may not have access to this project",4004:"Project not found"}[$]??`Unknown close code: ${$}`;return Error(`Connection closed: ${U}`)},oL=async($,v,U,D=3,_=1e4)=>{let I;for(let G=0;G<=D;G+=1){let J=new AbortController,X=globalThis.setTimeout(()=>J.abort(),_);try{let Q=await $(v,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(U),signal:J.signal});if(Q.ok)return;let Y=await Q.text();if(Q.status===401||Q.status===403)throw Error("Authentication failed. Check your public key.");if(Q.status>=400&&Q.status<500&&Q.status!==429)throw Error(`Client error (${Q.status}): ${Y}`);I=Error(Q.status===429?`Rate limited (429): ${Y}`:`Server error (${Q.status}): ${Y}`)}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);if(Y.startsWith("Authentication failed")||Y.startsWith("Client error ("))throw Q instanceof Error?Q:Error(Y);I=Q instanceof Error&&Q.name==="AbortError"?Error("Request timed out"):Q instanceof Error?Q:Error(String(Q))}finally{globalThis.clearTimeout(X)}if(G<D)await pL(oK*2**G)}throw Error(`Failed after ${D+1} attempts: ${I?.message??"Unknown error"}`)},tL=($)=>{return $.resourceLogs?.reduce((v,U)=>v+(U.scopeLogs?.reduce((D,_)=>D+(_.logRecords?.length??0),0)??0),0)??0},pL=async($)=>{await new Promise((v)=>globalThis.setTimeout(v,$))},$7=($,v,U)=>{return new D$("BAD_REQUEST",{message:v,data:{operationId:$,missingContext:U}})};var Gw=L(()=>{qv();_w();nK();k$();AL=w.object({projectId:w.string().uuid().optional().describe("Project to tail logs for. Auto-filled from CLI and SDK context when omitted."),filters:Uw.optional().describe("Optional filters applied by the tail WebSocket service.")}),jL=w.object({publicKey:w.string().min(1).describe("Public key for intake auth. Create or list one via the public key endpoints."),logs:w.custom(($)=>typeof $==="object"&&$!==null).describe("OTLP logs export request payload to send to the intake service.")}),EL=w.object({forwardedCount:w.number().int().nonnegative().describe("Number of log records accepted by the intake request."),failedCount:w.number().int().nonnegative().describe("Number of log records rejected by the intake request.")})});var aL="https://api.sazabi.com",U7="https://api.platform.sazabi.com",D7="sazabi-cli",eL="urn:ietf:params:oauth:grant-type:device_code",v7=($)=>{if($&&typeof $==="object")return $;return{}},I7=($)=>{let v=VD(new ZD(a9,{url:sL($.apiBaseUrl??aL),headers:async()=>new Headers({authorization:`Bearer ${await $.credentialProvider.getToken()}`}),fetch:$.fetch,customErrorResponseBodyDecoder:(D,_)=>{let I=GN(D);if(!I)return null;return new D$(I.code,{message:I.message,status:_.status,data:{operationId:I.operationId,missingContext:I.missingContext}})}})),U=aK({raw:v,credentialProvider:$.credentialProvider,fetch:$.fetch,intakeBaseUrl:$.intakeBaseUrl,tailBaseUrl:$.tailBaseUrl,webSocket:$.webSocket});return{raw:v,me:async()=>v.me({}),logs:{...U,query:async(D={})=>v.logs.query(await s$($.credentialProvider,D,y4.operationId))},organizations:{list:async()=>v.organizations.list({}),get:async(D)=>v.organizations.get(D),update:async(D)=>v.organizations.update(await vN($.credentialProvider,D))},members:{list:async(D={})=>v.members.list(await CU($.credentialProvider,D)),updateRole:async(D)=>v.members.updateRole(await CU($.credentialProvider,D)),remove:async(D)=>{let _=await CU($.credentialProvider,D);return v.members.remove({params:{userId:_.userId},query:{organizationId:_.organizationId}})}},publicKeys:{list:async(D={})=>v.publicKeys.list(await s$($.credentialProvider,D,E4.operationId)),get:async(D)=>v.publicKeys.get(await s$($.credentialProvider,D,x4.operationId)),create:async(D)=>v.publicKeys.create(await s$($.credentialProvider,D,R4.operationId)),update:async(D)=>v.publicKeys.update(await s$($.credentialProvider,D,C4.operationId)),delete:async(D)=>{let _=await s$($.credentialProvider,D,u4.operationId);return v7(await v.publicKeys.delete({params:{keyId:_.keyId},query:{projectId:_.projectId}}))}},secretKeys:{list:async(D={})=>v.secretKeys.list(D),get:async(D)=>v.secretKeys.get(D),create:async(D)=>v.secretKeys.create(D),update:async(D)=>v.secretKeys.update(D),delete:async(D)=>v7(await v.secretKeys.delete({params:{keyId:D.keyId}}))},search:{threads:async(D)=>v.search.threads(await s$($.credentialProvider,D,c4.operationId)),messages:async(D)=>v.search.messages(await s$($.credentialProvider,D,h4.operationId))},projects:{list:async(D={})=>v.projects.list(await $N($.credentialProvider,D)),get:async(D)=>v.projects.get(D)},messages:{list:async(D)=>v.messages.list(D),append:async(D)=>_7(v,await v.messages.append(IN(D)))},threads:{list:async(D={})=>v.threads.list(await _N($.credentialProvider,D)),get:async(D)=>v.threads.get(D),getStatus:async(D)=>v.threads.getStatus(D),create:async(D)=>_7(v,await v.threads.create(await DN($.credentialProvider,D))),update:async(D)=>v.threads.update(D)},runs:{list:async(D={})=>v.runs.list(await UN($.credentialProvider,D)),listForThread:async(D)=>v.runs.listForThread(D),get:async(D)=>v.runs.get(D)},dataSources:{listTypes:async()=>v.dataSources.listTypes({}),connections:{list:async(D={})=>v.dataSources.listConnections(await s$($.credentialProvider,D,A4.operationId)),get:async(D)=>v.dataSources.getConnection(D),create:async(D)=>v.dataSources.createConnection(await s$($.credentialProvider,D,j4.operationId))},streams:{list:async(D)=>v.dataSources.listStreams(D),get:async(D)=>v.dataSources.getStream(D),create:async(D)=>v.dataSources.createStream(D)}}}},G7=async($={})=>{let v=await Q7($.fetch)(w7($.apiBaseUrl??U7,"/device/code"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:$.clientId??D7,...$.scope?{scope:$.scope}:{}})}),U=await v.json();if(!v.ok)throw JN(U,v.status);let D=U;return{deviceCode:m4(D.device_code,"device_code"),userCode:m4(D.user_code,"user_code"),verificationUri:m4(D.verification_uri,"verification_uri"),verificationUriComplete:m4(D.verification_uri_complete,"verification_uri_complete"),expiresIn:Jw(D.expires_in,"expires_in"),interval:Jw(D.interval,"interval")}},J7=async($)=>{let v=await Q7($.fetch)(w7($.apiBaseUrl??U7,"/device/token"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:eL,device_code:$.deviceCode,client_id:$.clientId??D7})}),U=await v.json();if(v.ok){let _=U;return{status:"authorized",accessToken:m4(_.access_token,"access_token"),tokenType:m4(_.token_type,"token_type"),expiresIn:Jw(_.expires_in,"expires_in"),scope:typeof _.scope==="string"?_.scope:""}}let D=X7(U);if(!D)throw Error(`Device authorization failed with status ${v.status}`);if(D.error==="authorization_pending")return{status:"pending"};if(D.error==="slow_down")return{status:"pending",interval:10};if(D.error==="access_denied")return{status:"denied",message:D.errorDescription};if(D.error==="expired_token"||D.error==="invalid_grant")return{status:"expired",message:D.errorDescription};throw Error(D.errorDescription)},sL=($)=>{let v=$.replace(/\/+$/,"");return v.endsWith("/v1")?v:`${v}/v1`},w7=($,v)=>{return`${$.replace(/\/+$/,"")}/api/auth${v}`},$N=async($,v)=>{return CU($,v)},CU=async($,v)=>{let U=v.organizationId??await $.getOrganizationId?.();return U?{...v,organizationId:U}:v},vN=async($,v)=>{let U=v.organizationId??await $.getOrganizationId?.();if(!U)throw new D$("BAD_REQUEST",{message:"Organization ID is required",data:{operationId:"organizations.update",missingContext:["organizationId"]},status:400});return{...v,organizationId:U}},s$=async($,v,U)=>{let D=v.projectId??await $.getProjectId?.();if(!D)throw new D$("BAD_REQUEST",{message:"Project ID is required",data:{operationId:U,missingContext:["projectId"]},status:400});return{...v,projectId:D}},_N=async($,v)=>{let U=v.projectId??await $.getProjectId?.();return U?{...v,projectId:U}:v},UN=async($,v)=>{let U=v.projectId??await $.getProjectId?.();return U?{...v,projectId:U}:v},DN=async($,v)=>{let U=v.projectId??await $.getProjectId?.();return U?{...v,projectId:U}:v},IN=($)=>{return{threadId:$.threadId,message:$.message,wait:$.wait??!0,timeoutSeconds:$.timeoutSeconds??20}},GN=($)=>{if(!$||typeof $!=="object")return null;let v=$;if(typeof v.code!=="string"||typeof v.message!=="string"||typeof v.operationId!=="string")return null;return{code:v.code,message:v.message,operationId:v.operationId,missingContext:Array.isArray(v.missingContext)?v.missingContext.filter((U)=>typeof U==="string"):[]}},X7=($)=>{if(!$||typeof $!=="object")return null;let v=$;if(typeof v.error!=="string"||typeof v.error_description!=="string")return null;return{error:v.error,errorDescription:v.error_description}},JN=($,v)=>{let U=X7($);return Error(U?.errorDescription??`Device authorization failed with status ${v}`)},Q7=($)=>{return $??globalThis.fetch},_7=($,v)=>({result:v,poll:()=>$.runs.get({runId:v.runId}),waitForCompletion:async(U={})=>wN($,v,U)}),wN=async($,v,U)=>{if(v.completed)return v;let D=U.intervalMs??2000,_=Date.now(),I=v;while(!I.completed){if(U.timeoutMs!==void 0&&Date.now()-_>=U.timeoutMs)return I;await XN(D),I=await $.runs.get({runId:I.runId})}return I},XN=async($)=>{await new Promise((v)=>globalThis.setTimeout(v,$))},m4=($,v)=>{if(typeof $==="string")return $;throw Error(`Expected '${v}' to be a string.`)},Jw=($,v)=>{if(typeof $==="number")return $;throw Error(`Expected '${v}' to be a number.`)};var ww=L(()=>{qv();KX();vw();Gw();Gw()});var c$=($)=>({success:!0,value:$}),Tv=($,v,U)=>({success:!1,error:$,...v!==void 0&&{statusCode:v},...U!==void 0&&{errorPayload:U}}),k=($,v,U)=>{if(!$.success){let D=`${v}: ${$.error}`;if(U)return q($.errorPayload??D);return N(D)}return $.value};var e=L(()=>{n()});var YN="https://api.sazabi.com",f=async($)=>{try{return c$(await $())}catch(v){let U=PN(v),D=KN(v),_=v instanceof Error?v.message:String(v);return Tv(_,D,U)}},PN=($)=>{if(!$||typeof $!=="object")return;let v=$;if(typeof v.code!=="string"||typeof v.message!=="string"||!v.data||typeof v.data!=="object")return;let U=v.data;if(typeof U.operationId!=="string")return;return{code:v.code,message:v.message,operationId:U.operationId,missingContext:Array.isArray(U.missingContext)?U.missingContext.filter((D)=>typeof D==="string"):[]}},KN=($)=>{if(!$||typeof $!=="object")return;let v=$;return typeof v.status==="number"?v.status:void 0},Jv=($)=>{let v=I7({apiBaseUrl:$.baseUrl??YN,credentialProvider:{getToken:()=>$.token,getOrganizationId:()=>$.organizationId,getProjectId:()=>$.projectId},intakeBaseUrl:$.intakeBaseUrl,tailBaseUrl:$.tailBaseUrl});return{me:()=>f(()=>v.me()),logs:{tail:(U)=>f(()=>v.logs.tail(U)),forward:(U)=>f(()=>v.logs.forward(U))},organizations:{list:()=>f(()=>v.organizations.list()),get:(U)=>f(()=>v.organizations.get({organizationId:U})),rename:(U,D)=>f(()=>v.organizations.update({organizationId:D,name:U}))},members:{list:(U={})=>f(()=>v.members.list(U)),updateRole:(U,D,_)=>f(()=>v.members.updateRole({organizationId:_,userId:U,role:D})),remove:(U,D)=>f(()=>v.members.remove({organizationId:D,userId:U}))},projects:{list:(U={})=>f(()=>v.projects.list(U)),get:(U)=>f(()=>v.projects.get({projectId:U}))},threads:{list:(U={})=>f(()=>v.threads.list(U)),get:(U)=>f(()=>v.threads.get({threadId:U})),create:(U)=>f(()=>v.threads.create(U)),getStatus:(U)=>f(()=>v.threads.getStatus({threadId:U})),update:(U,D)=>f(()=>v.threads.update({threadId:U,status:D}))},messages:{list:(U,D={})=>f(()=>v.messages.list({threadId:U,...D})),append:(U,D,_,I)=>f(()=>v.messages.append({threadId:U,message:D,wait:_,timeoutSeconds:I}))},runs:{get:(U)=>f(()=>v.runs.get({runId:U}))},search:{threads:(U)=>f(()=>v.search.threads(U)),messages:(U)=>f(()=>v.search.messages(U))},publicKeys:{list:(U)=>f(()=>v.publicKeys.list(U)),get:(U,D)=>f(()=>v.publicKeys.get(D?{keyId:U,projectId:D}:{keyId:U})),create:(U)=>f(()=>v.publicKeys.create(U)),update:(U)=>f(()=>v.publicKeys.update(U)),delete:(U)=>f(()=>v.publicKeys.delete(U))},secretKeys:{list:(U)=>f(()=>v.secretKeys.list(U)),get:(U)=>f(()=>v.secretKeys.get({keyId:U})),create:(U)=>f(()=>v.secretKeys.create(U)),update:(U)=>f(()=>v.secretKeys.update(U)),delete:(U)=>f(()=>v.secretKeys.delete(U))},dataSources:{listTypes:()=>f(()=>v.dataSources.listTypes()),connections:{list:(U)=>f(()=>v.dataSources.connections.list(U)),get:(U)=>f(()=>v.dataSources.connections.get({connectionId:U})),create:(U)=>f(()=>v.dataSources.connections.create(U))},streams:{list:(U)=>f(()=>v.dataSources.streams.list({connectionId:U})),get:(U)=>f(()=>v.dataSources.streams.get({streamId:U})),create:(U)=>f(()=>v.dataSources.streams.create(U))}}}};var s6=L(()=>{ww();e()});var Y7;var P7=L(()=>{Y7={version:2,activeProfile:"default",profiles:{default:{}}}});import*as wv from"node:fs";import*as K7 from"node:os";import*as Yw from"node:path";var B$=($)=>{if($===void 0||$===null)return;if(typeof $==="string")return $.length>0?$:void 0;return},Xw,l4,VN=()=>{if(!wv.existsSync(Xw))wv.mkdirSync(Xw,{recursive:!0,mode:448})},Qw,V7=($)=>{Qw=$},O7=($)=>({token:B$($.token),activeOrganizationId:B$($.activeOrganizationId??$.organizationId),organizationName:B$($.organizationName),activeProjectId:B$($.activeProjectId??$.defaultProjectId),apiBaseUrl:B$($.apiBaseUrl),webBaseUrl:B$($.webBaseUrl),intakeBaseUrl:B$($.intakeBaseUrl),tailBaseUrl:B$($.tailBaseUrl),apiDomain:B$($.apiDomain),webDomain:B$($.webDomain),intakeDomain:B$($.intakeDomain),tailDomain:B$($.tailDomain),forwardPublicKey:B$($.forwardPublicKey)}),ON=($)=>({version:2,activeProfile:"default",profiles:{default:O7($)}}),WN=($)=>{let v=B$($.activeProfile)??"default",U=typeof $.profiles==="object"&&$.profiles!==null?$.profiles:{},D={};for(let[_,I]of Object.entries(U)){if(typeof I!=="object"||I===null)continue;D[_]=O7(I)}if(!D[v])D[v]={};return{version:2,activeProfile:v,profiles:D}},s=()=>{try{if(!wv.existsSync(l4))return c$(Y7);let $=wv.readFileSync(l4,"utf-8"),v=JSON.parse($),U=typeof v.version==="number"?v.version:void 0;if(U!==void 0&&U>2)return Tv("Settings file requires a newer CLI version. Please upgrade.");if(U===2)return c$(WN(v));let D=ON(v),_=J$(D);if(!_.success)return _;return c$(D)}catch($){let v=$ instanceof Error?$.message:String($);return Tv(`Failed to read settings: ${v}`)}},J$=($)=>{try{return VN(),wv.writeFileSync(l4,JSON.stringify($,null,2),{encoding:"utf-8",mode:384}),c$(void 0)}catch(v){let U=v instanceof Error?v.message:String(v);return Tv(`Failed to write settings: ${U}`)}},Xv=($,v)=>{if(v)return v;if(Qw)return Qw;let U=process.env.SAZABI_PROFILE?.trim();if(U)return U;return $.activeProfile??"default"},l$=($,v)=>{let U=Xv($,v),D=$.profiles[U];if(D)return c$(D);if(U==="default")return c$({});return Tv(`Profile '${U}' does not exist. Run 'sazabi profiles create ${U}' first.`)},Qv=()=>{let $=s();if(!$.success)return $;return l$($.value)},E$=($,v,U)=>{let D=Xv($,U);if(!$.profiles[D])return Tv(`Profile '${D}' does not exist. Run 'sazabi profiles create ${D}' first.`);return c$({...$,profiles:{...$.profiles,[D]:{...$.profiles[D],...v}}})};var h$=L(()=>{P7();e();Xw=Yw.join(K7.homedir(),".sazabi"),l4=Yw.join(Xw,"settings.json")});var $v=($)=>{let{cliFlag:v,globalUrl:U,globalDomain:D,buildUrlFromDomain:_,defaultUrl:I}=$;if(v)return v;let G=process.env.SAZABI_API_URL?.trim();if(G)return G;if(U)return U;if(D)return _(D);return I},R=($)=>{let{tokenFlag:v,organizationIdFlag:U,projectIdFlag:D,jsonMode:_}=$,I=v?.trim(),G=process.env.SAZABI_TOKEN?.trim(),J=process.env.SAZABI_ORGANIZATION_ID?.trim(),X=process.env.SAZABI_PROJECT_ID?.trim(),Q=k(Qv(),"Failed to read settings",_),Y=Q.token?.trim(),P=(I&&I.length>0?I:void 0)||(G&&G.length>0?G:void 0)||Y,V=I&&I.length>0?"flag":G&&G.length>0?"environment":"settings";if(!P||P.length===0){if(_)return q("Not authenticated. Set SAZABI_TOKEN, pass --token, run 'sazabi auth login', or run 'sazabi auth save <token>'.");return N("Not authenticated. Set SAZABI_TOKEN, pass --token, run 'sazabi auth login', or run 'sazabi auth save <token>'.")}let O,S;if(U)O=U,S="flag";else if(J&&J.length>0)O=J,S="environment";else if(Q.activeOrganizationId)O=Q.activeOrganizationId,S="settings";let B,h;if(D)B=D,h="flag";else if(X&&X.length>0)B=X,h="environment";else if(Q.activeProjectId)B=Q.activeProjectId,h="settings";return{token:P,type:"token",projectId:B,organizationId:O,tokenSource:V,organizationSource:S,projectSource:h}},y=($)=>{let v=k(Qv(),"Failed to read settings",$.jsonMode),U=$v({cliFlag:$.apiBaseUrlFlag,globalUrl:v.apiBaseUrl,globalDomain:v.apiDomain,buildUrlFromDomain:(D)=>`https://api.${D}`,defaultUrl:"https://api.sazabi.com"});return Jv({token:$.token,baseUrl:U,organizationId:$.organizationId,projectId:$.projectId})},W7,Pw,uU=async($)=>{let v=k(Qv(),"Failed to read settings",$.jsonMode),U=$v({cliFlag:$.apiBaseUrlFlag,globalUrl:v.apiBaseUrl,globalDomain:v.apiDomain,buildUrlFromDomain:(X)=>`https://api.${X}`,defaultUrl:"https://api.sazabi.com"}),D=`${$.token}@${U}@${$.projectId??""}`,_=W7.get(D);if(_)return _;let I=Pw.get(D);if(I)return I;if(!$.projectId){if($.jsonMode)return q("Project ID is required. Run 'sazabi projects use <project-id>' or set SAZABI_PROJECT_ID.");return N("Project ID is required. Run 'sazabi projects use <project-id>' or set SAZABI_PROJECT_ID.")}let G=$.projectId,J=(async()=>{let Q=await Jv({token:$.token,baseUrl:U,projectId:G}).projects.get(G),P=k(Q,"Failed to fetch project info",$.jsonMode).project;return W7.set(D,P),P})();Pw.set(D,J);try{return await J}finally{Pw.delete(D)}},$1=($)=>{if($)return $;let v=k(Qv(),"Failed to read settings");if(v.webBaseUrl)return v.webBaseUrl;if(v.webDomain)return`https://app.${v.webDomain}`;if(v.apiDomain)return`https://app.${v.apiDomain}`;if(v.apiBaseUrl?.includes("sazabi.dev"))return"https://app.sazabi.dev";return"https://app.sazabi.com"},yU=($,v,U)=>{return`${$1(U)}/projects/${$}/threads/${v}`},L7=($,v)=>{return`https://otlp.${v}.intake.${$}`};var w$=L(()=>{n();s6();e();h$();W7=new Map,Pw=new Map});var iU,_V=($)=>{iU.set($.name,$)},nU=($)=>{return iU.get($)},_1=()=>{return Array.from(iU.values())},UV=($)=>{return iU.has($)};var kw=L(()=>{iU=new Map});async function Sw($){let v=await $.publicKeys.list({limit:20});if(!v.success)return[];return v.value.publicKeys.map((U)=>({value:U.id,description:U.name}))}async function Bw($){let v=await $.secretKeys.list({limit:20});if(!v.success)return[];return v.value.secretKeys.map((U)=>({value:U.id,description:U.name}))}async function h3($){let v=await $.dataSources.connections.list();if(!v.success)return[];return v.value.connections.map((U)=>({value:U.id,description:U.displayName??void 0}))}async function JV($){let v=await $.members.list();if(!v.success)return[];return v.value.members.map((U)=>({value:U.userId,description:U.name??U.email}))}var f3=3000,c3,wV=async($,v,U)=>{try{let D=c3[$]?.[v];if(!D)return[];let _=Qv();if(!_.success)return[];let I=_.value,G=process.env.SAZABI_TOKEN?.trim()||I.token?.trim();if(!G)return[];let J=$v({globalUrl:I.apiBaseUrl,globalDomain:I.apiDomain,buildUrlFromDomain:(Y)=>`https://api.${Y}`,defaultUrl:"https://api.sazabi.com"}),X=Jv({token:G,baseUrl:J,organizationId:I.activeOrganizationId,projectId:I.activeProjectId});return(await Promise.race([D(X),new Promise((Y)=>setTimeout(()=>Y([]),f3))])).filter((Y)=>Y.value.startsWith(U))}catch{return[]}};var XV=L(()=>{s6();w$();h$();c3={threads:{get:async($)=>{let v=await $.threads.list({limit:20});if(!v.success)return[];return v.value.threads.map((U)=>({value:U.id,description:U.title??void 0}))}},projects:{use:async($)=>{let v=await $.projects.list();if(!v.success)return[];return v.value.projects.map((U)=>({value:U.id,description:U.name}))}},organizations:{use:async($)=>{let v=await $.organizations.list();if(!v.success)return[];return v.value.organizations.map((U)=>({value:U.id,description:U.name}))},rename:async($)=>{let v=await $.organizations.list();if(!v.success)return[];return v.value.organizations.map((U)=>({value:U.id,description:U.name}))}},"public-keys":{get:Sw,update:Sw,delete:Sw},"secret-keys":{get:Bw,update:Bw,delete:Bw},"data-sources":{"get-connection":h3},members:{"update-role":JV,remove:JV}}});var YV={};i$(YV,{parseCompletionContext:()=>l3,getCompletions:()=>i3});var r3,m3,l3=($)=>{let v=$.length>0?$:[""],U=v.length-1,D=v[U]??"";return{words:v,currentIndex:U,partial:D}},i3=async($)=>{let{words:v,currentIndex:U,partial:D}=$,_=v[U-1];if(_==="--profile")return t3(D);let I=o3(v),G=Math.max(0,I.length-(v.length-U));if(G===0)return n3(D);let J=I[0]??"",X=nU(J);if(!X)return[];if(G===1&&X.subcommands){if(D.startsWith("-"))return QV(X.options,I);return d3(X,D)}let Q=X.subcommands?I[1]:void 0,P=(Q?X.subcommands?.[Q]:void 0)?.options??X.options;if(D.startsWith("-"))return QV(P,I);if(_?.startsWith("--")){let V=_.slice(2);if(P?.[V]?.type==="string"){let S=`${J}:${Q??""}`,B=m3[S]?.[V]??r3[V];if(B)return B.filter((h)=>h.startsWith(D)).map((h)=>({value:h}));return[]}}return wV(J,Q??"",D)},n3=($)=>{let U=_1().filter((_)=>_.name.startsWith($)).map((_)=>({value:_.name,description:_.description})),D=[{value:"--help",description:"Show help"},{value:"--version",description:"Show version"},{value:"--profile",description:"Use a named profile"}];for(let _ of D)if(_.value.startsWith($))U.push(_);return U},d3=($,v)=>{if(!$.subcommands)return[];return Object.values($.subcommands).filter((U)=>U.name.startsWith(v)).map((U)=>({value:U.name,description:U.description}))},QV=($,v)=>{let U=v[v.length-1]??"",D=new Set(v.filter((I)=>I.startsWith("--")).map((I)=>I.replace(/=.*/,""))),_=[];if(!D.has("--help")&&"--help".startsWith(U))_.push({value:"--help",description:"Show help"});if(!D.has("--profile")&&"--profile".startsWith(U))_.push({value:"--profile",description:"Use a named profile"});if(!$)return _;for(let[I,G]of Object.entries($)){let J=`--${I}`;if(D.has(J))continue;if(!J.startsWith(U))continue;_.push({value:J,description:G.description})}return _},o3=($)=>{let v=[];for(let U=0;U<$.length;U++){let D=$[U];if(D==="--profile"&&U+1<$.length)U++;else if(D.startsWith("--profile="));else v.push(D)}return v},t3=($)=>{try{let v=s();if(!v.success)return[];return Object.keys(v.value.profiles).filter((U)=>U.startsWith($)).map((U)=>({value:U,description:U===v.value.activeProfile?"active":void 0}))}catch{return[]}};var PV=L(()=>{kw();h$();XV();r3={status:["regular","archived"],format:["json","text"]},m3={"members:update-role":{role:["admin","member"]},"messages:search":{role:["user","assistant"]},"messages:list":{role:["user","assistant"]}}});n();n();ww();import{spawn as LN}from"node:child_process";n();import{parseArgs as QN}from"node:util";var j=($,v,U={})=>{let D=QN({args:$,options:v,allowPositionals:Boolean(U.allowPositionals),strict:!1,tokens:!0}),_=Object.hasOwn(v,"json")&&D.values.json===!0,I=new Set(Object.keys(v)),G=new Set(Object.entries(v).map(([,X])=>X.short).filter((X)=>Boolean(X))),J=[];if(Array.isArray(D.tokens))for(let X of D.tokens){if(X.kind!=="option")continue;let Q=X.name,Y=Q.length>1;if(!(I.has(Q)||!Y&&G.has(Q))){let V=Y?`--${Q}`:`-${Q}`;if(!J.includes(V))J.push(V)}}for(let X of Object.keys(D.values))if(!I.has(X)){let Q=X.length>1?`--${X}`:`-${X}`;if(!J.includes(Q))J.push(Q)}if(J.length>0){let X=`Unknown option${J.length>1?"s":""}: ${J.join(", ")}`;if(_)q(X);N(X)}for(let[X,Q]of Object.entries(v))if(Q.type==="string"&&D.values[X]===!0){let P=`Option ${X.length===1?`-${X}`:`--${X}`} requires a value`;if(_)q(P);N(P)}for(let[X,Q]of Object.entries(v)){let Y=D.values[X];if(Q.type==="string"&&typeof Y==="string"){if(Y.startsWith("--")||Y.length===2&&Y[0]==="-"&&/[a-zA-Z]/.test(Y.charAt(1))){let O=`Option ${X.length===1?`-${X}`:`--${X}`} received "${Y}" as its value. Did you forget to provide a value?`;if(_)q(O);N(O)}}}return{values:D.values,positionals:D.positionals}};w$();var fU=($,v)=>{let U=$?.json;if(!U||U.type!=="boolean")throw Error(`${v} must include a boolean --json option (enforced by CommandBuilder)`)};class N7{name;description;handler;subcommands;options;examples;positionalArgs;allowNoJson=!1;constructor($,v,U){this.name=$,this.description=v,this.handler=U}withOptions($){return this.options=$,this}withSubcommands($){return this.subcommands=$,this}withExamples($){return this.examples=$,this}withPositionalArgs($){return this.positionalArgs=$,this}build(){if(!this.handler&&!this.subcommands)throw Error(`Subcommand "${this.name}" must have either a handler or subcommands`);if(!this.allowNoJson&&this.handler)fU(this.options,`Subcommand "${this.name}"`);if(!this.allowNoJson&&this.subcommands){for(let[$,v]of Object.entries(this.subcommands))if(!v.subcommands)fU(v.options,`Subcommand "${this.name} ${$}"`)}return{name:this.name,description:this.description,handler:this.handler,subcommands:this.subcommands,options:this.options,examples:this.examples,positionalArgs:this.positionalArgs}}allowWithoutJson(){return this.allowNoJson=!0,this}}class q7{name;description;handler;subcommands;options;examples;positionalArgs;allowNoJson=!1;constructor($,v){this.name=$,this.description=v}withHandler($){return this.handler=$,this}withSubcommands($){return this.subcommands=$,this}withOptions($){return this.options=$,this}withExamples($){return this.examples=$,this}withPositionalArgs($){return this.positionalArgs=$,this}build(){if(!this.handler&&!this.subcommands)throw Error(`Command "${this.name}" must have either a handler or subcommands`);if(!this.allowNoJson){if(this.handler)fU(this.options,`Command "${this.name}"`);if(this.subcommands)for(let[$,v]of Object.entries(this.subcommands)){if(v.subcommands)continue;fU(v.options,`Subcommand "${this.name} ${$}"`)}}return{name:this.name,description:this.description,handler:this.handler,subcommands:this.subcommands,options:this.options,examples:this.examples,positionalArgs:this.positionalArgs}}allowWithoutJson(){return this.allowNoJson=!0,this}}var o=($,v)=>{return new q7($,v)},z=($,v,U)=>{return new N7($,v,U)};e();h$();var i4=($)=>{if($==="flag")return"from flag";if($==="environment")return"from environment";return"from settings"},NN=async($={})=>{let v=R({jsonMode:$.json}),U=y({token:v.token,organizationId:v.organizationId,projectId:v.projectId,apiBaseUrlFlag:$.apiBaseUrl,jsonMode:$.json}),D=k(await U.me(),"Failed to fetch authentication details",$.json);if($.json){M({credential:D,activeOrganizationId:v.organizationId,activeProjectId:v.projectId,tokenSource:v.tokenSource,organizationSource:v.organizationSource,projectSource:v.projectSource});return}if(Y$("Authentication"),D.credentialType==="user"){_$({Type:`User token (${i4(v.tokenSource)})`,User:D.user.name??D.user.email,Email:D.user.email,"Active Organization":v.organizationId&&v.organizationSource?`${v.organizationId} (${i4(v.organizationSource)})`:G$("(none)"),"Active Project":v.projectId&&v.projectSource?`${v.projectId} (${i4(v.projectSource)})`:G$("(none)"),Organizations:D.organizations.length.toString(),"Dashboard URL":$1()});return}if(D.credentialType==="secret"){_$({Type:`Secret key (${i4(v.tokenSource)})`,Organization:D.organization.name,"Key Name":D.keyName,"Active Project":v.projectId&&v.projectSource?`${v.projectId} (${i4(v.projectSource)})`:G$("(none)"),"Dashboard URL":$1()});return}_$({Type:`Partner key (${i4(v.tokenSource)})`,Superorganization:D.superorganization.name,"Dashboard URL":$1()})},qN=async($,v={})=>{let U=$.trim();if(!U){if(v.json)return q("Token is required.");return N("Token is required.")}let D=k(s(),"Failed to read settings",v.json);await k7({token:U,options:v,cliSettings:D,status:"saved"})},kN=($)=>{let v=process.platform,U,D;if(v==="darwin")U="open",D=[$];else if(v==="win32")U="cmd",D=["/c","start","",$];else U="xdg-open",D=[$];let _=LN(U,D,{detached:!0,stdio:"ignore"});_.on("error",()=>{}),_.unref()},HN=($)=>new Promise((v)=>setTimeout(v,$)),FN=async($={})=>{let v=k(s(),"Failed to read settings",$.json),U=Xv(v),D=v.profiles[U]??{},_=ZN(D,$.apiBaseUrl),I=MN(_,$.authBaseUrl),G;try{G=await G7({apiBaseUrl:I})}catch(Y){let P=Y instanceof Error?Y.message:String(Y);if($.json)return q(`Failed to initiate login: ${P}`);return N(`Failed to initiate login: ${P}`)}let J=TN(G.verificationUriComplete,$.webBaseUrl),X=new Date(Date.now()+G.expiresIn*1000),Q=G.interval*1000;if(!$.json)r(),Y$("Login to Sazabi"),r(),r$("Enter this code in your browser:"),r(),r$(O$.bold(G.userCode),4),r(),r$(`Opening ${O$.info(J)}`),r(),kN(J),c("Waiting for authorization...");while(new Date<X){await HN(Q);try{let Y=await J7({apiBaseUrl:I,deviceCode:G.deviceCode});if(Y.status==="pending"){Q=(Y.interval??G.interval)*1000;continue}if(Y.status==="denied"){if($.json)return q("Authorization was denied.");return r(),N("Authorization was denied.")}if(Y.status==="expired"){if($.json)return q("Authorization request expired. Please try again.");return r(),N("Authorization request expired. Please try again.")}await k7({token:Y.accessToken,options:$,cliSettings:v,status:"authorized"});return}catch(Y){let P=Y instanceof Error?Y.message:String(Y);if($.json)return q(`Authorization failed: ${P}`);return r(),N(`Authorization failed: ${P}`)}}if($.json)return q("Authorization request expired. Please try again.");return r(),N("Authorization request expired. Please try again.")},bN=($)=>{let v=k(s(),"Failed to read settings",$.json),U=k(l$(v),"Failed to resolve profile",$.json),D=Boolean(U.token),_=k(E$(v,{token:void 0,activeOrganizationId:void 0,organizationName:void 0,activeProjectId:void 0}),"Failed to update profile",$.json);if(k(J$(_),"Failed to remove credentials",$.json),$.json){M({removed:D});return}if(D){u("Logged out successfully.");return}c("No credentials were saved.")},k7=async({token:$,options:v,cliSettings:U,status:D})=>{let _=y({token:$,apiBaseUrlFlag:v.apiBaseUrl,jsonMode:v.json}),I=k(await _.me(),"Failed to resolve authenticated context",v.json);if(D==="authorized"&&I.credentialType!=="user"){if(v.json)return q("Expected a user session from device authorization.");return N("Expected a user session from device authorization.")}let G=Xv(U),J=U.profiles[G]?U:{...U,profiles:{...U.profiles,[G]:{}}},X=J.profiles[G],Q=await gN({client:_,credential:I,currentProjectId:X.activeProjectId,jsonMode:v.json}),Y=k(E$(J,{token:$,activeOrganizationId:Q.activeOrganizationId,organizationName:Q.activeOrganizationName,activeProjectId:Q.activeProjectId}),"Failed to update profile",v.json);if(k(J$(Y),"Failed to save credentials",v.json),v.json){M({status:D,credential:I,activeOrganizationId:Q.activeOrganizationId,activeProjectId:Q.activeProjectId,projects:Q.projects});return}if(r(),u(D==="authorized"?"Successfully authenticated!":"Saved token."),r(),BN({credential:I,activeOrganizationName:Q.activeOrganizationName,activeProjectId:Q.activeProjectId,projects:Q.projects}),Q.projects.length>0){r(),Y$("Available Projects");for(let P of Q.projects){let O=P.id===Q.activeProjectId?O$.success(" (active)"):"";r$(`${P.name} (${P.region})${O}`)}}},gN=async({client:$,credential:v,currentProjectId:U,jsonMode:D})=>{if(v.credentialType==="partner")return{projects:[]};let _=v.credentialType==="user"?v.activeOrganizationId??v.organizations[0]?.id:v.organization.id,I=v.credentialType==="user"?v.organizations.find((J)=>J.id===_)?.name:v.organization.name,G=_?k(await $.projects.list({organizationId:_}),"Failed to fetch projects",D).projects:[];return{activeOrganizationId:_,activeOrganizationName:I,activeProjectId:SN(G,U),projects:G}},SN=($,v)=>{if(v&&$.some((U)=>U.id===v))return v;return $[0]?.id},BN=({credential:$,activeOrganizationName:v,activeProjectId:U,projects:D})=>{if($.credentialType==="user"){_$({Type:"User token",User:$.user.name??$.user.email,Organizations:$.organizations.length.toString(),"Active Organization":v??"(none)","Active Project":D.find((_)=>_.id===U)?.name??"(none)"});return}if($.credentialType==="secret"){_$({Type:"Secret key",Organization:$.organization.name,"Key Name":$.keyName,"Active Project":D.find((_)=>_.id===U)?.name??"(none)"});return}_$({Type:"Partner key",Superorganization:$.superorganization.name})},ZN=($,v)=>{return $v({cliFlag:v,globalUrl:$.apiBaseUrl,globalDomain:$.apiDomain,buildUrlFromDomain:(U)=>`https://api.${U}`,defaultUrl:"https://api.sazabi.com"})},MN=($,v)=>{if(v)return v;try{let U=new URL($);if(["localhost","127.0.0.1"].includes(U.hostname)&&["15005","15009"].includes(U.port))return U.port="15001",U.toString().replace(/\/$/,"");if(U.hostname==="api.sazabi.com")return U.hostname="api.platform.sazabi.com",U.toString().replace(/\/$/,"");if(U.hostname==="api.sazabi.dev")return U.hostname="api.platform.sazabi.dev",U.toString().replace(/\/$/,"");return U.toString().replace(/\/$/,"")}catch{return $}},TN=($,v)=>{if(!v)return $;let U=new URL($),D=new URL(v);return U.protocol=D.protocol,U.host=D.host,U.toString()},H7=o("auth","").withSubcommands({login:z("login","Authenticate via browser",async($)=>{let{values:v,positionals:U}=j($,{json:{type:"boolean"},"api-base-url":{type:"string"},"auth-base-url":{type:"string"},"web-base-url":{type:"string"}},{allowPositionals:!0});if(U.length>0){let D=U.join(", ");if(v.json)return q(`Unexpected arguments: ${D}`);return N(`Unexpected arguments: ${D}`)}await FN({json:v.json,apiBaseUrl:v["api-base-url"],authBaseUrl:v["auth-base-url"],webBaseUrl:v["web-base-url"]})}).withOptions({json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override public API base URL"},"auth-base-url":{type:"string",description:"Override Better Auth API base URL"},"web-base-url":{type:"string",description:"Override web app base URL"}}).withExamples(["sazabi auth login # Authenticate via browser","sazabi auth login --api-base-url http://localhost:15009 --auth-base-url http://localhost:15001 --web-base-url https://localhost:5173 # Authenticate against local development"]).build(),save:z("save","Save an existing bearer token",async($)=>{let{values:v,positionals:U}=j($,{json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),D=U[0];if(!D){if(v.json)return q("Token is required.");return N("Token is required.")}if(U.length>1){let _=U.slice(1).join(", ");if(v.json)return q(`Unexpected arguments: ${_}`);return N(`Unexpected arguments: ${_}`)}await qN(D,{json:v.json,apiBaseUrl:v["api-base-url"]})}).withPositionalArgs("<token>").withOptions({json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi auth save sazabi_secret_xxx # Save a secret key for future commands","sazabi auth save session_token_xxx --api-base-url http://localhost:15009 # Save a token against local development"]).build(),logout:z("logout","Remove saved credentials",async($)=>{let{values:v,positionals:U}=j($,{json:{type:"boolean"}},{allowPositionals:!0});if(U.length>0){let D=U.join(", ");if(v.json)return q(`Unexpected arguments: ${D}`);return N(`Unexpected arguments: ${D}`)}bN({json:v.json})}).withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(["sazabi auth logout # Remove saved credentials"]).build(),whoami:z("whoami","Display current authentication context",async($)=>{let{values:v,positionals:U}=j($,{json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0});if(U.length>0){let D=U.join(", ");if(v.json)return q(`Unexpected arguments: ${D}`);return N(`Unexpected arguments: ${D}`)}await NN({json:v.json,apiBaseUrl:v["api-base-url"]})}).withOptions({json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi auth whoami # Show current context","sazabi auth whoami --json # Output as JSON"]).build()}).withExamples(["sazabi auth login # Authenticate via browser","sazabi auth save sazabi_secret_xxx # Save an existing token","sazabi auth logout # Remove saved credentials","sazabi auth whoami # Show current context"]).build();n();var F7=()=>`
398
398
  _sazabi() {
399
399
  local -a completions
400
400
  local line IFS=$'\\n'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sazabi/cli",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "The Sazabi CLI",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",