@sazabi/cli 6.1.0 → 6.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -113,7 +113,7 @@ ${Ze("OPTIONS")}`,s+=`
|
|
|
113
113
|
|
|
114
114
|
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let s=a[1];if(t===a[0]){i(a);continue}if(e.external){let l=e.external.registry.get(a[0])?.id;if(t!==a[0]&&l){i(a);continue}}if(e.metadataRegistry.get(a[0])?.id){i(a);continue}if(s.cycle){i(a);continue}if(s.count>1){if(e.reused==="ref"){i(a);continue}}}}function co(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(a)=>{let s=e.seen.get(a);if(s.ref===null)return;let c=s.def??s.schema,l={...c},u=s.ref;if(s.ref=null,u){r(u);let p=e.seen.get(u),m=p.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))c.allOf=c.allOf??[],c.allOf.push(m);else Object.assign(c,m);if(Object.assign(c,l),a._zod.parent===u)for(let y in c){if(y==="$ref"||y==="allOf")continue;if(!(y in l))delete c[y]}if(m.$ref&&p.def)for(let y in c){if(y==="$ref"||y==="allOf")continue;if(y in p.def&&JSON.stringify(c[y])===JSON.stringify(p.def[y]))delete c[y]}}let d=a._zod.parent;if(d&&d!==u){r(d);let p=e.seen.get(d);if(p?.schema.$ref){if(c.$ref=p.schema.$ref,p.def)for(let m in c){if(m==="$ref"||m==="allOf")continue;if(m in p.def&&JSON.stringify(c[m])===JSON.stringify(p.def[m]))delete c[m]}}}e.override({zodSchema:a,jsonSchema:c,path:s.path??[]})};for(let a of[...e.seen.entries()].reverse())r(a[0]);let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,n.def??n.schema);let i=e.external?.defs??{};for(let a of e.seen.entries()){let s=a[1];if(s.def&&s.defId)i[s.defId]=s.def}if(e.external);else if(Object.keys(i).length>0)if(e.target==="draft-2020-12")o.$defs=i;else o.definitions=i;try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Gr(t,"input",e.processors),output:Gr(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function bt(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return bt(r.element,n);if(r.type==="set")return bt(r.valueType,n);if(r.type==="lazy")return bt(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return bt(r.innerType,n);if(r.type==="intersection")return bt(r.left,n)||bt(r.right,n);if(r.type==="record"||r.type==="map")return bt(r.keyType,n)||bt(r.valueType,n);if(r.type==="pipe")return bt(r.in,n)||bt(r.out,n);if(r.type==="object"){for(let o in r.shape)if(bt(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(bt(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(bt(o,n))return!0;if(r.rest&&bt(r.rest,n))return!0;return!1}return!1}var df=(e,t={})=>(n)=>{let r=ao({...n,processors:t});return Pe(e,r),so(r,e),co(r,e)},Gr=(e,t,n={})=>(r)=>{let{libraryOptions:o,target:i}=r??{},a=ao({...o??{},target:i,io:t,processors:n});return Pe(e,a),so(a,e),co(a,e)};var Ta=L(()=>{Oa()});function rl(e,t){if("_idmap"in e){let r=e,o=ao({...t,processors:tl}),i={};for(let c of r._idmap.entries()){let[l,u]=c;Pe(u,o)}let a={},s={registry:r,uri:t?.uri,defs:i};o.external=s;for(let c of r._idmap.entries()){let[l,u]=c;so(o,u),a[l]=co(o,u)}if(Object.keys(i).length>0){let c=o.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[c]:i}}return{schemas:a}}let n=ao({...t,processors:tl});return Pe(e,n),so(n,e),co(n,e)}var JU,pf=(e,t,n,r)=>{let o=n;o.type="string";let{minimum:i,maximum:a,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof i==="number")o.minLength=i;if(typeof a==="number")o.maxLength=a;if(s){if(o.format=JU[s]??s,o.format==="")delete o.format;if(s==="time")delete o.format}if(l)o.contentEncoding=l;if(c&&c.size>0){let u=[...c];if(u.length===1)o.pattern=u[0].source;else if(u.length>1)o.allOf=[...u.map((d)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))]}},mf=(e,t,n,r)=>{let o=n,{minimum:i,maximum:a,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;if(typeof s==="string"&&s.includes("int"))o.type="integer";else o.type="number";if(typeof u==="number")if(t.target==="draft-04"||t.target==="openapi-3.0")o.minimum=u,o.exclusiveMinimum=!0;else o.exclusiveMinimum=u;if(typeof i==="number"){if(o.minimum=i,typeof u==="number"&&t.target!=="draft-04")if(u>=i)delete o.minimum;else delete o.exclusiveMinimum}if(typeof l==="number")if(t.target==="draft-04"||t.target==="openapi-3.0")o.maximum=l,o.exclusiveMaximum=!0;else o.exclusiveMaximum=l;if(typeof a==="number"){if(o.maximum=a,typeof l==="number"&&t.target!=="draft-04")if(l<=a)delete o.maximum;else delete o.exclusiveMaximum}if(typeof c==="number")o.multipleOf=c},gf=(e,t,n,r)=>{n.type="boolean"},hf=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},ff=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},yf=(e,t,n,r)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},bf=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},vf=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},Sf=(e,t,n,r)=>{n.not={}},If=(e,t,n,r)=>{},kf=(e,t,n,r)=>{},wf=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},Cf=(e,t,n,r)=>{let o=e._zod.def,i=sa(o.entries);if(i.every((a)=>typeof a==="number"))n.type="number";if(i.every((a)=>typeof a==="string"))n.type="string";n.enum=i},Pf=(e,t,n,r)=>{let o=e._zod.def,i=[];for(let a of o.values)if(a===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else i.push(Number(a));else i.push(a);if(i.length===0);else if(i.length===1){let a=i[0];if(n.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[a];else n.const=a}else{if(i.every((a)=>typeof a==="number"))n.type="number";if(i.every((a)=>typeof a==="string"))n.type="string";if(i.every((a)=>typeof a==="boolean"))n.type="boolean";if(i.every((a)=>a===null))n.type="null";n.enum=i}},Of=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},xf=(e,t,n,r)=>{let o=n,i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},Af=(e,t,n,r)=>{let o=n,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:s,mime:c}=e._zod.bag;if(a!==void 0)i.minLength=a;if(s!==void 0)i.maxLength=s;if(c)if(c.length===1)i.contentMediaType=c[0],Object.assign(o,i);else Object.assign(o,i),o.anyOf=c.map((l)=>({contentMediaType:l}));else Object.assign(o,i)},Tf=(e,t,n,r)=>{n.type="boolean"},_f=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},jf=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},Rf=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},Ef=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},Lf=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},zf=(e,t,n,r)=>{let o=n,i=e._zod.def,{minimum:a,maximum:s}=e._zod.bag;if(typeof a==="number")o.minItems=a;if(typeof s==="number")o.maxItems=s;o.type="array",o.items=Pe(i.element,t,{...r,path:[...r.path,"items"]})},Df=(e,t,n,r)=>{let o=n,i=e._zod.def;o.type="object",o.properties={};let a=i.shape;for(let l in a)o.properties[l]=Pe(a[l],t,{...r,path:[...r.path,"properties",l]});let s=new Set(Object.keys(a)),c=new Set([...s].filter((l)=>{let u=i.shape[l]._zod;if(t.io==="input")return u.optin===void 0;else return u.optout===void 0}));if(c.size>0)o.required=Array.from(c);if(i.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")o.additionalProperties=!1}else if(i.catchall)o.additionalProperties=Pe(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},nl=(e,t,n,r)=>{let o=e._zod.def,i=o.inclusive===!1,a=o.options.map((s,c)=>Pe(s,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));if(i)n.oneOf=a;else n.anyOf=a},$f=(e,t,n,r)=>{let o=e._zod.def,i=Pe(o.left,t,{...r,path:[...r.path,"allOf",0]}),a=Pe(o.right,t,{...r,path:[...r.path,"allOf",1]}),s=(l)=>("allOf"in l)&&Object.keys(l).length===1,c=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];n.allOf=c},Nf=(e,t,n,r)=>{let o=n,i=e._zod.def;o.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((p,m)=>Pe(p,t,{...r,path:[...r.path,a,m]})),l=i.rest?Pe(i.rest,t,{...r,path:[...r.path,s,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(o.prefixItems=c,l)o.items=l}else if(t.target==="openapi-3.0"){if(o.items={anyOf:c},l)o.items.anyOf.push(l);if(o.minItems=c.length,!l)o.maxItems=c.length}else if(o.items=c,l)o.additionalItems=l;let{minimum:u,maximum:d}=e._zod.bag;if(typeof u==="number")o.minItems=u;if(typeof d==="number")o.maxItems=d},Uf=(e,t,n,r)=>{let o=n,i=e._zod.def;o.type="object";let a=i.keyType,c=a._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let u=Pe(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let d of c)o.patternProperties[d.source]=u}else{if(t.target==="draft-07"||t.target==="draft-2020-12")o.propertyNames=Pe(i.keyType,t,{...r,path:[...r.path,"propertyNames"]});o.additionalProperties=Pe(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let l=a._zod.values;if(l){let u=[...l].filter((d)=>typeof d==="string"||typeof d==="number");if(u.length>0)o.required=u}},Mf=(e,t,n,r)=>{let o=e._zod.def,i=Pe(o.innerType,t,r),a=t.seen.get(e);if(t.target==="openapi-3.0")a.ref=o.innerType,n.nullable=!0;else n.anyOf=[i,{type:"null"}]},Ff=(e,t,n,r)=>{let o=e._zod.def;Pe(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType},Bf=(e,t,n,r)=>{let o=e._zod.def;Pe(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},Gf=(e,t,n,r)=>{let o=e._zod.def;Pe(o.innerType,t,r);let i=t.seen.get(e);if(i.ref=o.innerType,t.io==="input")n._prefault=JSON.parse(JSON.stringify(o.defaultValue))},Kf=(e,t,n,r)=>{let o=e._zod.def;Pe(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType;let a;try{a=o.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}n.default=a},qf=(e,t,n,r)=>{let o=e._zod.def,i=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;Pe(i,t,r);let a=t.seen.get(e);a.ref=i},Wf=(e,t,n,r)=>{let o=e._zod.def;Pe(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType,n.readOnly=!0},Vf=(e,t,n,r)=>{let o=e._zod.def;Pe(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType},ol=(e,t,n,r)=>{let o=e._zod.def;Pe(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType},Hf=(e,t,n,r)=>{let o=e._zod.innerType;Pe(o,t,r);let i=t.seen.get(e);i.ref=o},tl;var _a=L(()=>{Ta();ae();JU={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},tl={string:pf,number:mf,boolean:gf,bigint:hf,symbol:ff,null:yf,undefined:bf,void:vf,never:Sf,any:If,unknown:kf,date:wf,enum:Cf,literal:Pf,nan:Of,template_literal:xf,file:Af,success:Tf,custom:_f,function:jf,transform:Rf,map:Ef,set:Lf,array:zf,object:Df,union:nl,intersection:$f,tuple:Nf,record:Uf,nullable:Mf,nonoptional:Ff,default:Bf,prefault:Gf,catch:Kf,pipe:qf,readonly:Wf,promise:Vf,optional:ol,lazy:Hf}});class Zf{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";this.ctx=ao({processors:tl,target:t,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,t={path:[],schemaPath:[]}){return Pe(e,this.ctx,t)}emit(e,t){if(t){if(t.cycles)this.ctx.cycles=t.cycles;if(t.reused)this.ctx.reused=t.reused;if(t.external)this.ctx.external=t.external}so(this.ctx,e);let n=co(this.ctx,e),{"~standard":r,...o}=n;return o}}var LC=L(()=>{_a();Ta()});var zC={};var DC=()=>{};var Nn={};hn(Nn,{$ZodAny:()=>Vm,$ZodArray:()=>Xm,$ZodAsyncError:()=>bn,$ZodBase64:()=>$m,$ZodBase64URL:()=>Nm,$ZodBigInt:()=>Oc,$ZodBigIntFormat:()=>Gm,$ZodBoolean:()=>ba,$ZodCIDRv4:()=>Lm,$ZodCIDRv6:()=>zm,$ZodCUID:()=>km,$ZodCUID2:()=>wm,$ZodCatch:()=>fg,$ZodCheck:()=>je,$ZodCheckBigIntFormat:()=>Yp,$ZodCheckEndsWith:()=>lm,$ZodCheckGreaterThan:()=>yc,$ZodCheckIncludes:()=>sm,$ZodCheckLengthEquals:()=>om,$ZodCheckLessThan:()=>fc,$ZodCheckLowerCase:()=>im,$ZodCheckMaxLength:()=>tm,$ZodCheckMaxSize:()=>Xp,$ZodCheckMimeType:()=>dm,$ZodCheckMinLength:()=>nm,$ZodCheckMinSize:()=>Qp,$ZodCheckMultipleOf:()=>Zp,$ZodCheckNumberFormat:()=>Jp,$ZodCheckOverwrite:()=>pm,$ZodCheckProperty:()=>um,$ZodCheckRegex:()=>rm,$ZodCheckSizeEquals:()=>em,$ZodCheckStartsWith:()=>cm,$ZodCheckStringFormat:()=>Ar,$ZodCheckUpperCase:()=>am,$ZodCodec:()=>Sa,$ZodCustom:()=>Cg,$ZodCustomStringFormat:()=>Fm,$ZodDate:()=>Ym,$ZodDefault:()=>pg,$ZodDiscriminatedUnion:()=>tg,$ZodE164:()=>Um,$ZodEmail:()=>bm,$ZodEmoji:()=>Sm,$ZodEncodeError:()=>zo,$ZodEnum:()=>ag,$ZodError:()=>pa,$ZodExactOptional:()=>ug,$ZodFile:()=>cg,$ZodFunction:()=>Ig,$ZodGUID:()=>fm,$ZodIPv4:()=>jm,$ZodIPv6:()=>Rm,$ZodISODate:()=>Am,$ZodISODateTime:()=>xm,$ZodISODuration:()=>_m,$ZodISOTime:()=>Tm,$ZodIntersection:()=>ng,$ZodJWT:()=>Mm,$ZodKSUID:()=>Om,$ZodLazy:()=>wg,$ZodLiteral:()=>sg,$ZodMAC:()=>Em,$ZodMap:()=>rg,$ZodNaN:()=>yg,$ZodNanoID:()=>Im,$ZodNever:()=>Zm,$ZodNonOptional:()=>gg,$ZodNull:()=>Wm,$ZodNullable:()=>dg,$ZodNumber:()=>Pc,$ZodNumberFormat:()=>Bm,$ZodObject:()=>Lw,$ZodObjectJIT:()=>Qm,$ZodOptional:()=>Ac,$ZodPipe:()=>bg,$ZodPrefault:()=>mg,$ZodPromise:()=>kg,$ZodReadonly:()=>vg,$ZodRealError:()=>wt,$ZodRecord:()=>og,$ZodRegistry:()=>Ch,$ZodSet:()=>ig,$ZodString:()=>No,$ZodStringFormat:()=>Ae,$ZodSuccess:()=>hg,$ZodSymbol:()=>Km,$ZodTemplateLiteral:()=>Sg,$ZodTransform:()=>lg,$ZodTuple:()=>xc,$ZodType:()=>me,$ZodULID:()=>Cm,$ZodURL:()=>vm,$ZodUUID:()=>ym,$ZodUndefined:()=>qm,$ZodUnion:()=>va,$ZodUnknown:()=>Hm,$ZodVoid:()=>Jm,$ZodXID:()=>Pm,$ZodXor:()=>eg,$brand:()=>ip,$constructor:()=>P,$input:()=>wh,$output:()=>kh,Doc:()=>vc,JSONSchema:()=>zC,JSONSchemaGenerator:()=>Zf,NEVER:()=>rp,TimePrecision:()=>Ah,_any:()=>Zh,_array:()=>nf,_base64:()=>Wc,_base64url:()=>Vc,_bigint:()=>Bh,_boolean:()=>Mh,_catch:()=>KU,_check:()=>RC,_cidrv4:()=>Kc,_cidrv6:()=>qc,_coercedBigint:()=>Gh,_coercedBoolean:()=>Fh,_coercedDate:()=>ef,_coercedNumber:()=>Lh,_coercedString:()=>Oh,_cuid:()=>$c,_cuid2:()=>Nc,_custom:()=>rf,_date:()=>Qh,_decode:()=>sc,_decodeAsync:()=>lc,_default:()=>FU,_discriminatedUnion:()=>TU,_e164:()=>Hc,_email:()=>_c,_emoji:()=>zc,_encode:()=>ac,_encodeAsync:()=>cc,_endsWith:()=>zr,_enum:()=>zU,_file:()=>of,_float32:()=>Dh,_float64:()=>$h,_gt:()=>Sn,_gte:()=>yt,_guid:()=>xa,_includes:()=>Er,_int:()=>zh,_int32:()=>Nh,_int64:()=>Kh,_intersection:()=>_U,_ipv4:()=>Bc,_ipv6:()=>Gc,_isoDate:()=>_h,_isoDateTime:()=>Th,_isoDuration:()=>Rh,_isoTime:()=>jh,_jwt:()=>Zc,_ksuid:()=>Fc,_lazy:()=>HU,_length:()=>Fo,_literal:()=>$U,_lowercase:()=>jr,_lt:()=>vn,_lte:()=>zt,_mac:()=>xh,_map:()=>EU,_max:()=>zt,_maxLength:()=>Mo,_maxSize:()=>io,_mime:()=>Dr,_min:()=>yt,_minLength:()=>$n,_minSize:()=>In,_multipleOf:()=>ro,_nan:()=>tf,_nanoid:()=>Dc,_nativeEnum:()=>DU,_negative:()=>Yc,_never:()=>Yh,_nonnegative:()=>Qc,_nonoptional:()=>BU,_nonpositive:()=>Xc,_normalize:()=>$r,_null:()=>Hh,_nullable:()=>MU,_number:()=>Eh,_optional:()=>UU,_overwrite:()=>nn,_parse:()=>Cr,_parseAsync:()=>Pr,_pipe:()=>qU,_positive:()=>Jc,_promise:()=>ZU,_property:()=>el,_readonly:()=>WU,_record:()=>RU,_refine:()=>af,_regex:()=>_r,_safeDecode:()=>dc,_safeDecodeAsync:()=>mc,_safeEncode:()=>uc,_safeEncodeAsync:()=>pc,_safeParse:()=>Or,_safeParseAsync:()=>xr,_set:()=>LU,_size:()=>Uo,_slugify:()=>Fr,_startsWith:()=>Lr,_string:()=>Ph,_stringFormat:()=>Br,_stringbool:()=>uf,_success:()=>GU,_superRefine:()=>sf,_symbol:()=>Wh,_templateLiteral:()=>VU,_toLowerCase:()=>Ur,_toUpperCase:()=>Mr,_transform:()=>NU,_trim:()=>Nr,_tuple:()=>jU,_uint32:()=>Uh,_uint64:()=>qh,_ulid:()=>Uc,_undefined:()=>Vh,_union:()=>xU,_unknown:()=>Jh,_uppercase:()=>Rr,_url:()=>Aa,_uuid:()=>jc,_uuidv4:()=>Rc,_uuidv6:()=>Ec,_uuidv7:()=>Lc,_void:()=>Xh,_xid:()=>Mc,_xor:()=>AU,clone:()=>ft,config:()=>$e,createStandardJSONSchemaMethod:()=>Gr,createToJSONSchemaMethod:()=>df,decode:()=>X$,decodeAsync:()=>eN,describe:()=>cf,encode:()=>Y$,encodeAsync:()=>Q$,extractDefs:()=>so,finalize:()=>co,flattenError:()=>ma,formatError:()=>ga,globalConfig:()=>ia,globalRegistry:()=>Xe,initializeContext:()=>ao,isValidBase64:()=>Dm,isValidBase64URL:()=>_w,isValidJWT:()=>jw,locales:()=>Pa,meta:()=>lf,parse:()=>rc,parseAsync:()=>ic,prettifyError:()=>fp,process:()=>Pe,regexes:()=>Vt,registry:()=>Tc,safeDecode:()=>nN,safeDecodeAsync:()=>rN,safeEncode:()=>tN,safeEncodeAsync:()=>oN,safeParse:()=>bp,safeParseAsync:()=>vp,toDotPath:()=>pw,toJSONSchema:()=>rl,treeifyError:()=>hp,util:()=>G,version:()=>mm});var Dt=L(()=>{ae();hc();Ih();_a();LC();DC();Sr();Sp();yp();Pg();bc();gm();Oa();EC();Ta()});var il={};hn(il,{endsWith:()=>zr,gt:()=>Sn,gte:()=>yt,includes:()=>Er,length:()=>Fo,lowercase:()=>jr,lt:()=>vn,lte:()=>zt,maxLength:()=>Mo,maxSize:()=>io,mime:()=>Dr,minLength:()=>$n,minSize:()=>In,multipleOf:()=>ro,negative:()=>Yc,nonnegative:()=>Qc,nonpositive:()=>Xc,normalize:()=>$r,overwrite:()=>nn,positive:()=>Jc,property:()=>el,regex:()=>_r,size:()=>Uo,slugify:()=>Fr,startsWith:()=>Lr,toLowerCase:()=>Ur,toUpperCase:()=>Mr,trim:()=>Nr,uppercase:()=>Rr});var al=L(()=>{Dt()});var Kr={};hn(Kr,{ZodISODate:()=>cl,ZodISODateTime:()=>sl,ZodISODuration:()=>ul,ZodISOTime:()=>ll,date:()=>Yf,datetime:()=>Jf,duration:()=>Qf,time:()=>Xf});function Jf(e){return Th(sl,e)}function Yf(e){return _h(cl,e)}function Xf(e){return jh(ll,e)}function Qf(e){return Rh(ul,e)}var sl,cl,ll,ul;var ja=L(()=>{Dt();Ea();sl=P("ZodISODateTime",(e,t)=>{xm.init(e,t),Te.init(e,t)});cl=P("ZodISODate",(e,t)=>{Am.init(e,t),Te.init(e,t)});ll=P("ZodISOTime",(e,t)=>{Tm.init(e,t),Te.init(e,t)});ul=P("ZodISODuration",(e,t)=>{_m.init(e,t),Te.init(e,t)})});var $C=(e,t)=>{pa.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(n)=>ga(e,n)},flatten:{value:(n)=>ma(e,n)},addIssue:{value:(n)=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Ir,2)}},addIssues:{value:(n)=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Ir,2)}},isEmpty:{get(){return e.issues.length===0}}})},XU,Ct;var ey=L(()=>{Dt();Dt();ae();XU=P("ZodError",$C),Ct=P("ZodError",$C,{Parent:Error})});var ty,ny,oy,ry,iy,ay,sy,cy,ly,uy,dy,py;var my=L(()=>{Dt();ey();ty=Cr(Ct),ny=Pr(Ct),oy=Or(Ct),ry=xr(Ct),iy=ac(Ct),ay=sc(Ct),sy=cc(Ct),cy=lc(Ct),ly=uc(Ct),uy=dc(Ct),dy=pc(Ct),py=mc(Ct)});var Ra={};hn(Ra,{ZodAny:()=>Iy,ZodArray:()=>Py,ZodBase64:()=>Ol,ZodBase64URL:()=>xl,ZodBigInt:()=>Jr,ZodBigIntFormat:()=>_l,ZodBoolean:()=>Zr,ZodCIDRv4:()=>Cl,ZodCIDRv6:()=>Pl,ZodCUID:()=>yl,ZodCUID2:()=>bl,ZodCatch:()=>Vy,ZodCodec:()=>Nl,ZodCustom:()=>Ka,ZodCustomStringFormat:()=>Vr,ZodDate:()=>Ua,ZodDefault:()=>Fy,ZodDiscriminatedUnion:()=>xy,ZodE164:()=>Al,ZodEmail:()=>gl,ZodEmoji:()=>hl,ZodEnum:()=>qr,ZodExactOptional:()=>Ny,ZodFile:()=>Dy,ZodFunction:()=>nb,ZodGUID:()=>La,ZodIPv4:()=>kl,ZodIPv6:()=>wl,ZodIntersection:()=>Ay,ZodJWT:()=>Tl,ZodKSUID:()=>Il,ZodLazy:()=>Qy,ZodLiteral:()=>zy,ZodMAC:()=>gy,ZodMap:()=>Ey,ZodNaN:()=>Zy,ZodNanoID:()=>fl,ZodNever:()=>wy,ZodNonOptional:()=>Dl,ZodNull:()=>vy,ZodNullable:()=>My,ZodNumber:()=>Hr,ZodNumberFormat:()=>Go,ZodObject:()=>Fa,ZodOptional:()=>zl,ZodPipe:()=>$l,ZodPrefault:()=>Gy,ZodPromise:()=>tb,ZodReadonly:()=>Jy,ZodRecord:()=>Ga,ZodSet:()=>Ly,ZodString:()=>Wr,ZodStringFormat:()=>Te,ZodSuccess:()=>Wy,ZodSymbol:()=>yy,ZodTemplateLiteral:()=>Xy,ZodTransform:()=>$y,ZodTuple:()=>_y,ZodType:()=>fe,ZodULID:()=>vl,ZodURL:()=>Na,ZodUUID:()=>kn,ZodUndefined:()=>by,ZodUnion:()=>Ba,ZodUnknown:()=>ky,ZodVoid:()=>Cy,ZodXID:()=>Sl,ZodXor:()=>Oy,_ZodString:()=>ml,_default:()=>By,_function:()=>GP,any:()=>IP,array:()=>Ma,base64:()=>rP,base64url:()=>iP,bigint:()=>fP,boolean:()=>fy,catch:()=>Hy,check:()=>KP,cidrv4:()=>nP,cidrv6:()=>oP,codec:()=>MP,cuid:()=>HC,cuid2:()=>ZC,custom:()=>qP,date:()=>wP,describe:()=>WP,discriminatedUnion:()=>TP,e164:()=>aP,email:()=>NC,emoji:()=>WC,enum:()=>El,exactOptional:()=>Uy,file:()=>DP,float32:()=>pP,float64:()=>mP,function:()=>GP,guid:()=>UC,hash:()=>dP,hex:()=>uP,hostname:()=>lP,httpUrl:()=>qC,instanceof:()=>HP,int:()=>pl,int32:()=>gP,int64:()=>yP,intersection:()=>Ty,ipv4:()=>QC,ipv6:()=>tP,json:()=>JP,jwt:()=>sP,keyof:()=>CP,ksuid:()=>XC,lazy:()=>eb,literal:()=>zP,looseObject:()=>xP,looseRecord:()=>jP,mac:()=>eP,map:()=>RP,meta:()=>VP,nan:()=>UP,nanoid:()=>VC,nativeEnum:()=>LP,never:()=>jl,nonoptional:()=>qy,null:()=>Sy,nullable:()=>Da,nullish:()=>$P,number:()=>hy,object:()=>PP,optional:()=>za,partialRecord:()=>_P,pipe:()=>$a,prefault:()=>Ky,preprocess:()=>YP,promise:()=>BP,readonly:()=>Yy,record:()=>Ry,refine:()=>ob,set:()=>EP,strictObject:()=>OP,string:()=>dl,stringFormat:()=>cP,stringbool:()=>ZP,success:()=>NP,superRefine:()=>rb,symbol:()=>vP,templateLiteral:()=>FP,transform:()=>Ll,tuple:()=>jy,uint32:()=>hP,uint64:()=>bP,ulid:()=>JC,undefined:()=>SP,union:()=>Rl,unknown:()=>Bo,url:()=>KC,uuid:()=>MC,uuidv4:()=>FC,uuidv6:()=>BC,uuidv7:()=>GC,void:()=>kP,xid:()=>YC,xor:()=>AP});function dl(e){return Ph(Wr,e)}function NC(e){return _c(gl,e)}function UC(e){return xa(La,e)}function MC(e){return jc(kn,e)}function FC(e){return Rc(kn,e)}function BC(e){return Ec(kn,e)}function GC(e){return Lc(kn,e)}function KC(e){return Aa(Na,e)}function qC(e){return Aa(Na,{protocol:/^https?$/,hostname:Vt.domain,...G.normalizeParams(e)})}function WC(e){return zc(hl,e)}function VC(e){return Dc(fl,e)}function HC(e){return $c(yl,e)}function ZC(e){return Nc(bl,e)}function JC(e){return Uc(vl,e)}function YC(e){return Mc(Sl,e)}function XC(e){return Fc(Il,e)}function QC(e){return Bc(kl,e)}function eP(e){return xh(gy,e)}function tP(e){return Gc(wl,e)}function nP(e){return Kc(Cl,e)}function oP(e){return qc(Pl,e)}function rP(e){return Wc(Ol,e)}function iP(e){return Vc(xl,e)}function aP(e){return Hc(Al,e)}function sP(e){return Zc(Tl,e)}function cP(e,t,n={}){return Br(Vr,e,t,n)}function lP(e){return Br(Vr,"hostname",Vt.hostname,e)}function uP(e){return Br(Vr,"hex",Vt.hex,e)}function dP(e,t){let n=t?.enc??"hex",r=`${e}_${n}`,o=Vt[r];if(!o)throw Error(`Unrecognized hash format: ${r}`);return Br(Vr,r,o,t)}function hy(e){return Eh(Hr,e)}function pl(e){return zh(Go,e)}function pP(e){return Dh(Go,e)}function mP(e){return $h(Go,e)}function gP(e){return Nh(Go,e)}function hP(e){return Uh(Go,e)}function fy(e){return Mh(Zr,e)}function fP(e){return Bh(Jr,e)}function yP(e){return Kh(_l,e)}function bP(e){return qh(_l,e)}function vP(e){return Wh(yy,e)}function SP(e){return Vh(by,e)}function Sy(e){return Hh(vy,e)}function IP(){return Zh(Iy)}function Bo(){return Jh(ky)}function jl(e){return Yh(wy,e)}function kP(e){return Xh(Cy,e)}function wP(e){return Qh(Ua,e)}function Ma(e,t){return nf(Py,e,t)}function CP(e){let t=e._zod.def.shape;return El(Object.keys(t))}function PP(e,t){let n={type:"object",shape:e??{},...G.normalizeParams(t)};return new Fa(n)}function OP(e,t){return new Fa({type:"object",shape:e,catchall:jl(),...G.normalizeParams(t)})}function xP(e,t){return new Fa({type:"object",shape:e,catchall:Bo(),...G.normalizeParams(t)})}function Rl(e,t){return new Ba({type:"union",options:e,...G.normalizeParams(t)})}function AP(e,t){return new Oy({type:"union",options:e,inclusive:!1,...G.normalizeParams(t)})}function TP(e,t,n){return new xy({type:"union",options:t,discriminator:e,...G.normalizeParams(n)})}function Ty(e,t){return new Ay({type:"intersection",left:e,right:t})}function jy(e,t,n){let r=t instanceof me,o=r?n:t;return new _y({type:"tuple",items:e,rest:r?t:null,...G.normalizeParams(o)})}function Ry(e,t,n){return new Ga({type:"record",keyType:e,valueType:t,...G.normalizeParams(n)})}function _P(e,t,n){let r=ft(e);return r._zod.values=void 0,new Ga({type:"record",keyType:r,valueType:t,...G.normalizeParams(n)})}function jP(e,t,n){return new Ga({type:"record",keyType:e,valueType:t,mode:"loose",...G.normalizeParams(n)})}function RP(e,t,n){return new Ey({type:"map",keyType:e,valueType:t,...G.normalizeParams(n)})}function EP(e,t){return new Ly({type:"set",valueType:e,...G.normalizeParams(t)})}function El(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new qr({type:"enum",entries:n,...G.normalizeParams(t)})}function LP(e,t){return new qr({type:"enum",entries:e,...G.normalizeParams(t)})}function zP(e,t){return new zy({type:"literal",values:Array.isArray(e)?e:[e],...G.normalizeParams(t)})}function DP(e){return of(Dy,e)}function Ll(e){return new $y({type:"transform",transform:e})}function za(e){return new zl({type:"optional",innerType:e})}function Uy(e){return new Ny({type:"optional",innerType:e})}function Da(e){return new My({type:"nullable",innerType:e})}function $P(e){return za(Da(e))}function By(e,t){return new Fy({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():G.shallowClone(t)}})}function Ky(e,t){return new Gy({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():G.shallowClone(t)}})}function qy(e,t){return new Dl({type:"nonoptional",innerType:e,...G.normalizeParams(t)})}function NP(e){return new Wy({type:"success",innerType:e})}function Hy(e,t){return new Vy({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}function UP(e){return tf(Zy,e)}function $a(e,t){return new $l({type:"pipe",in:e,out:t})}function MP(e,t,n){return new Nl({type:"pipe",in:e,out:t,transform:n.decode,reverseTransform:n.encode})}function Yy(e){return new Jy({type:"readonly",innerType:e})}function FP(e,t){return new Xy({type:"template_literal",parts:e,...G.normalizeParams(t)})}function eb(e){return new Qy({type:"lazy",getter:e})}function BP(e){return new tb({type:"promise",innerType:e})}function GP(e){return new nb({type:"function",input:Array.isArray(e?.input)?jy(e?.input):e?.input??Ma(Bo()),output:e?.output??Bo()})}function KP(e){let t=new je({check:"custom"});return t._zod.check=e,t}function qP(e,t){return rf(Ka,e??(()=>!0),t)}function ob(e,t={}){return af(Ka,e,t)}function rb(e){return sf(e)}function HP(e,t={}){let n=new Ka({type:"custom",check:"custom",fn:(r)=>r instanceof e,abort:!0,...G.normalizeParams(t)});return n._zod.bag.Class=e,n._zod.check=(r)=>{if(!(r.value instanceof e))r.issues.push({code:"invalid_type",expected:e.name,input:r.value,inst:n,path:[...n._zod.def.path??[]]})},n}function JP(e){let t=eb(()=>Rl([dl(e),hy(),fy(),Sy(),Ma(t),Ry(dl(),t)]));return t}function YP(e,t){return $a(Ll(e),t)}var fe,ml,Wr,Te,gl,La,kn,Na,hl,fl,yl,bl,vl,Sl,Il,kl,gy,wl,Cl,Pl,Ol,xl,Al,Tl,Vr,Hr,Go,Zr,Jr,_l,yy,by,vy,Iy,ky,wy,Cy,Ua,Py,Fa,Ba,Oy,xy,Ay,_y,Ga,Ey,Ly,qr,zy,Dy,$y,zl,Ny,My,Fy,Gy,Dl,Wy,Vy,Zy,$l,Nl,Jy,Xy,Qy,tb,nb,Ka,WP,VP,ZP=(...e)=>uf({Codec:Nl,Boolean:Zr,String:Wr},...e);var Ea=L(()=>{Dt();Dt();_a();Ta();al();ja();my();fe=P("ZodType",(e,t)=>(me.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Gr(e,"input"),output:Gr(e,"output")}}),e.toJSONSchema=df(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(G.mergeDefs(t,{checks:[...t.checks??[],...n.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0}),e.with=e.check,e.clone=(n,r)=>ft(e,n,r),e.brand=()=>e,e.register=(n,r)=>(n.add(e,r),e),e.parse=(n,r)=>ty(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>oy(e,n,r),e.parseAsync=async(n,r)=>ny(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>ry(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>iy(e,n,r),e.decode=(n,r)=>ay(e,n,r),e.encodeAsync=async(n,r)=>sy(e,n,r),e.decodeAsync=async(n,r)=>cy(e,n,r),e.safeEncode=(n,r)=>ly(e,n,r),e.safeDecode=(n,r)=>uy(e,n,r),e.safeEncodeAsync=async(n,r)=>dy(e,n,r),e.safeDecodeAsync=async(n,r)=>py(e,n,r),e.refine=(n,r)=>e.check(ob(n,r)),e.superRefine=(n)=>e.check(rb(n)),e.overwrite=(n)=>e.check(nn(n)),e.optional=()=>za(e),e.exactOptional=()=>Uy(e),e.nullable=()=>Da(e),e.nullish=()=>za(Da(e)),e.nonoptional=(n)=>qy(e,n),e.array=()=>Ma(e),e.or=(n)=>Rl([e,n]),e.and=(n)=>Ty(e,n),e.transform=(n)=>$a(e,Ll(n)),e.default=(n)=>By(e,n),e.prefault=(n)=>Ky(e,n),e.catch=(n)=>Hy(e,n),e.pipe=(n)=>$a(e,n),e.readonly=()=>Yy(e),e.describe=(n)=>{let r=e.clone();return Xe.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return Xe.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Xe.get(e);let r=e.clone();return Xe.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=(n)=>n(e),e)),ml=P("_ZodString",(e,t)=>{No.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(r,o,i)=>pf(e,r,o,i);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(_r(...r)),e.includes=(...r)=>e.check(Er(...r)),e.startsWith=(...r)=>e.check(Lr(...r)),e.endsWith=(...r)=>e.check(zr(...r)),e.min=(...r)=>e.check($n(...r)),e.max=(...r)=>e.check(Mo(...r)),e.length=(...r)=>e.check(Fo(...r)),e.nonempty=(...r)=>e.check($n(1,...r)),e.lowercase=(r)=>e.check(jr(r)),e.uppercase=(r)=>e.check(Rr(r)),e.trim=()=>e.check(Nr()),e.normalize=(...r)=>e.check($r(...r)),e.toLowerCase=()=>e.check(Ur()),e.toUpperCase=()=>e.check(Mr()),e.slugify=()=>e.check(Fr())}),Wr=P("ZodString",(e,t)=>{No.init(e,t),ml.init(e,t),e.email=(n)=>e.check(_c(gl,n)),e.url=(n)=>e.check(Aa(Na,n)),e.jwt=(n)=>e.check(Zc(Tl,n)),e.emoji=(n)=>e.check(zc(hl,n)),e.guid=(n)=>e.check(xa(La,n)),e.uuid=(n)=>e.check(jc(kn,n)),e.uuidv4=(n)=>e.check(Rc(kn,n)),e.uuidv6=(n)=>e.check(Ec(kn,n)),e.uuidv7=(n)=>e.check(Lc(kn,n)),e.nanoid=(n)=>e.check(Dc(fl,n)),e.guid=(n)=>e.check(xa(La,n)),e.cuid=(n)=>e.check($c(yl,n)),e.cuid2=(n)=>e.check(Nc(bl,n)),e.ulid=(n)=>e.check(Uc(vl,n)),e.base64=(n)=>e.check(Wc(Ol,n)),e.base64url=(n)=>e.check(Vc(xl,n)),e.xid=(n)=>e.check(Mc(Sl,n)),e.ksuid=(n)=>e.check(Fc(Il,n)),e.ipv4=(n)=>e.check(Bc(kl,n)),e.ipv6=(n)=>e.check(Gc(wl,n)),e.cidrv4=(n)=>e.check(Kc(Cl,n)),e.cidrv6=(n)=>e.check(qc(Pl,n)),e.e164=(n)=>e.check(Hc(Al,n)),e.datetime=(n)=>e.check(Jf(n)),e.date=(n)=>e.check(Yf(n)),e.time=(n)=>e.check(Xf(n)),e.duration=(n)=>e.check(Qf(n))});Te=P("ZodStringFormat",(e,t)=>{Ae.init(e,t),ml.init(e,t)}),gl=P("ZodEmail",(e,t)=>{bm.init(e,t),Te.init(e,t)});La=P("ZodGUID",(e,t)=>{fm.init(e,t),Te.init(e,t)});kn=P("ZodUUID",(e,t)=>{ym.init(e,t),Te.init(e,t)});Na=P("ZodURL",(e,t)=>{vm.init(e,t),Te.init(e,t)});hl=P("ZodEmoji",(e,t)=>{Sm.init(e,t),Te.init(e,t)});fl=P("ZodNanoID",(e,t)=>{Im.init(e,t),Te.init(e,t)});yl=P("ZodCUID",(e,t)=>{km.init(e,t),Te.init(e,t)});bl=P("ZodCUID2",(e,t)=>{wm.init(e,t),Te.init(e,t)});vl=P("ZodULID",(e,t)=>{Cm.init(e,t),Te.init(e,t)});Sl=P("ZodXID",(e,t)=>{Pm.init(e,t),Te.init(e,t)});Il=P("ZodKSUID",(e,t)=>{Om.init(e,t),Te.init(e,t)});kl=P("ZodIPv4",(e,t)=>{jm.init(e,t),Te.init(e,t)});gy=P("ZodMAC",(e,t)=>{Em.init(e,t),Te.init(e,t)});wl=P("ZodIPv6",(e,t)=>{Rm.init(e,t),Te.init(e,t)});Cl=P("ZodCIDRv4",(e,t)=>{Lm.init(e,t),Te.init(e,t)});Pl=P("ZodCIDRv6",(e,t)=>{zm.init(e,t),Te.init(e,t)});Ol=P("ZodBase64",(e,t)=>{$m.init(e,t),Te.init(e,t)});xl=P("ZodBase64URL",(e,t)=>{Nm.init(e,t),Te.init(e,t)});Al=P("ZodE164",(e,t)=>{Um.init(e,t),Te.init(e,t)});Tl=P("ZodJWT",(e,t)=>{Mm.init(e,t),Te.init(e,t)});Vr=P("ZodCustomStringFormat",(e,t)=>{Fm.init(e,t),Te.init(e,t)});Hr=P("ZodNumber",(e,t)=>{Pc.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(r,o,i)=>mf(e,r,o,i),e.gt=(r,o)=>e.check(Sn(r,o)),e.gte=(r,o)=>e.check(yt(r,o)),e.min=(r,o)=>e.check(yt(r,o)),e.lt=(r,o)=>e.check(vn(r,o)),e.lte=(r,o)=>e.check(zt(r,o)),e.max=(r,o)=>e.check(zt(r,o)),e.int=(r)=>e.check(pl(r)),e.safe=(r)=>e.check(pl(r)),e.positive=(r)=>e.check(Sn(0,r)),e.nonnegative=(r)=>e.check(yt(0,r)),e.negative=(r)=>e.check(vn(0,r)),e.nonpositive=(r)=>e.check(zt(0,r)),e.multipleOf=(r,o)=>e.check(ro(r,o)),e.step=(r,o)=>e.check(ro(r,o)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??0.5),e.isFinite=!0,e.format=n.format??null});Go=P("ZodNumberFormat",(e,t)=>{Bm.init(e,t),Hr.init(e,t)});Zr=P("ZodBoolean",(e,t)=>{ba.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>gf(e,n,r,o)});Jr=P("ZodBigInt",(e,t)=>{Oc.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(r,o,i)=>hf(e,r,o,i),e.gte=(r,o)=>e.check(yt(r,o)),e.min=(r,o)=>e.check(yt(r,o)),e.gt=(r,o)=>e.check(Sn(r,o)),e.gte=(r,o)=>e.check(yt(r,o)),e.min=(r,o)=>e.check(yt(r,o)),e.lt=(r,o)=>e.check(vn(r,o)),e.lte=(r,o)=>e.check(zt(r,o)),e.max=(r,o)=>e.check(zt(r,o)),e.positive=(r)=>e.check(Sn(BigInt(0),r)),e.negative=(r)=>e.check(vn(BigInt(0),r)),e.nonpositive=(r)=>e.check(zt(BigInt(0),r)),e.nonnegative=(r)=>e.check(yt(BigInt(0),r)),e.multipleOf=(r,o)=>e.check(ro(r,o));let n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null});_l=P("ZodBigIntFormat",(e,t)=>{Gm.init(e,t),Jr.init(e,t)});yy=P("ZodSymbol",(e,t)=>{Km.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ff(e,n,r,o)});by=P("ZodUndefined",(e,t)=>{qm.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>bf(e,n,r,o)});vy=P("ZodNull",(e,t)=>{Wm.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>yf(e,n,r,o)});Iy=P("ZodAny",(e,t)=>{Vm.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>If(e,n,r,o)});ky=P("ZodUnknown",(e,t)=>{Hm.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>kf(e,n,r,o)});wy=P("ZodNever",(e,t)=>{Zm.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Sf(e,n,r,o)});Cy=P("ZodVoid",(e,t)=>{Jm.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>vf(e,n,r,o)});Ua=P("ZodDate",(e,t)=>{Ym.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(r,o,i)=>wf(e,r,o,i),e.min=(r,o)=>e.check(yt(r,o)),e.max=(r,o)=>e.check(zt(r,o));let n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});Py=P("ZodArray",(e,t)=>{Xm.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>zf(e,n,r,o),e.element=t.element,e.min=(n,r)=>e.check($n(n,r)),e.nonempty=(n)=>e.check($n(1,n)),e.max=(n,r)=>e.check(Mo(n,r)),e.length=(n,r)=>e.check(Fo(n,r)),e.unwrap=()=>e.element});Fa=P("ZodObject",(e,t)=>{Qm.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Df(e,n,r,o),G.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>El(Object.keys(e._zod.def.shape)),e.catchall=(n)=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Bo()}),e.loose=()=>e.clone({...e._zod.def,catchall:Bo()}),e.strict=()=>e.clone({...e._zod.def,catchall:jl()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=(n)=>G.extend(e,n),e.safeExtend=(n)=>G.safeExtend(e,n),e.merge=(n)=>G.merge(e,n),e.pick=(n)=>G.pick(e,n),e.omit=(n)=>G.omit(e,n),e.partial=(...n)=>G.partial(zl,e,n[0]),e.required=(...n)=>G.required(Dl,e,n[0])});Ba=P("ZodUnion",(e,t)=>{va.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>nl(e,n,r,o),e.options=t.options});Oy=P("ZodXor",(e,t)=>{Ba.init(e,t),eg.init(e,t),e._zod.processJSONSchema=(n,r,o)=>nl(e,n,r,o),e.options=t.options});xy=P("ZodDiscriminatedUnion",(e,t)=>{Ba.init(e,t),tg.init(e,t)});Ay=P("ZodIntersection",(e,t)=>{ng.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>$f(e,n,r,o)});_y=P("ZodTuple",(e,t)=>{xc.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Nf(e,n,r,o),e.rest=(n)=>e.clone({...e._zod.def,rest:n})});Ga=P("ZodRecord",(e,t)=>{og.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Uf(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});Ey=P("ZodMap",(e,t)=>{rg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ef(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...n)=>e.check(In(...n)),e.nonempty=(n)=>e.check(In(1,n)),e.max=(...n)=>e.check(io(...n)),e.size=(...n)=>e.check(Uo(...n))});Ly=P("ZodSet",(e,t)=>{ig.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Lf(e,n,r,o),e.min=(...n)=>e.check(In(...n)),e.nonempty=(n)=>e.check(In(1,n)),e.max=(...n)=>e.check(io(...n)),e.size=(...n)=>e.check(Uo(...n))});qr=P("ZodEnum",(e,t)=>{ag.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(r,o,i)=>Cf(e,r,o,i),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{let i={};for(let a of r)if(n.has(a))i[a]=t.entries[a];else throw Error(`Key ${a} not found in enum`);return new qr({...t,checks:[],...G.normalizeParams(o),entries:i})},e.exclude=(r,o)=>{let i={...t.entries};for(let a of r)if(n.has(a))delete i[a];else throw Error(`Key ${a} not found in enum`);return new qr({...t,checks:[],...G.normalizeParams(o),entries:i})}});zy=P("ZodLiteral",(e,t)=>{sg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Pf(e,n,r,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});Dy=P("ZodFile",(e,t)=>{cg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Af(e,n,r,o),e.min=(n,r)=>e.check(In(n,r)),e.max=(n,r)=>e.check(io(n,r)),e.mime=(n,r)=>e.check(Dr(Array.isArray(n)?n:[n],r))});$y=P("ZodTransform",(e,t)=>{lg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Rf(e,n,r,o),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new zo(e.constructor.name);n.addIssue=(i)=>{if(typeof i==="string")n.issues.push(G.issue(i,n.value,t));else{let a=i;if(a.fatal)a.continue=!1;a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=e),n.issues.push(G.issue(a))}};let o=t.transform(n.value,n);if(o instanceof Promise)return o.then((i)=>(n.value=i,n));return n.value=o,n}});zl=P("ZodOptional",(e,t)=>{Ac.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ol(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});Ny=P("ZodExactOptional",(e,t)=>{ug.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ol(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});My=P("ZodNullable",(e,t)=>{dg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Mf(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});Fy=P("ZodDefault",(e,t)=>{pg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Bf(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});Gy=P("ZodPrefault",(e,t)=>{mg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Gf(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});Dl=P("ZodNonOptional",(e,t)=>{gg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ff(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});Wy=P("ZodSuccess",(e,t)=>{hg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Tf(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});Vy=P("ZodCatch",(e,t)=>{fg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Kf(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});Zy=P("ZodNaN",(e,t)=>{yg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Of(e,n,r,o)});$l=P("ZodPipe",(e,t)=>{bg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>qf(e,n,r,o),e.in=t.in,e.out=t.out});Nl=P("ZodCodec",(e,t)=>{$l.init(e,t),Sa.init(e,t)});Jy=P("ZodReadonly",(e,t)=>{vg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Wf(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});Xy=P("ZodTemplateLiteral",(e,t)=>{Sg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>xf(e,n,r,o)});Qy=P("ZodLazy",(e,t)=>{wg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Hf(e,n,r,o),e.unwrap=()=>e._zod.def.getter()});tb=P("ZodPromise",(e,t)=>{kg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Vf(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});nb=P("ZodFunction",(e,t)=>{Ig.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>jf(e,n,r,o)});Ka=P("ZodCustom",(e,t)=>{Cg.init(e,t),fe.init(e,t),e._zod.processJSONSchema=(n,r,o)=>_f(e,n,r,o)});WP=cf,VP=lf});function tM(e){$e({customError:e})}function nM(){return $e().customError}var eM,ib;var XP=L(()=>{Dt();eM={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};(function(e){})(ib||(ib={}))});function rM(e,t){let n=e.$schema;if(n==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(n==="http://json-schema.org/draft-07/schema#")return"draft-7";if(n==="http://json-schema.org/draft-04/schema#")return"draft-4";return t??"draft-2020-12"}function iM(e,t){if(!e.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let n=e.slice(1).split("/").filter(Boolean);if(n.length===0)return t.rootSchema;let r=t.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===r){let o=n[1];if(!o||!t.defs[o])throw Error(`Reference not found: ${e}`);return t.defs[o]}throw Error(`Reference not found: ${e}`)}function QP(e,t){if(e.not!==void 0){if(typeof e.not==="object"&&Object.keys(e.not).length===0)return Y.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let o=e.$ref;if(t.refs.has(o))return t.refs.get(o);if(t.processing.has(o))return Y.lazy(()=>{if(!t.refs.has(o))throw Error(`Circular reference not resolved: ${o}`);return t.refs.get(o)});t.processing.add(o);let i=iM(o,t),a=ct(i,t);return t.refs.set(o,a),t.processing.delete(o),a}if(e.enum!==void 0){let o=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&o.length===1&&o[0]===null)return Y.null();if(o.length===0)return Y.never();if(o.length===1)return Y.literal(o[0]);if(o.every((a)=>typeof a==="string"))return Y.enum(o);let i=o.map((a)=>Y.literal(a));if(i.length<2)return i[0];return Y.union([i[0],i[1],...i.slice(2)])}if(e.const!==void 0)return Y.literal(e.const);let n=e.type;if(Array.isArray(n)){let o=n.map((i)=>{let a={...e,type:i};return QP(a,t)});if(o.length===0)return Y.never();if(o.length===1)return o[0];return Y.union(o)}if(!n)return Y.any();let r;switch(n){case"string":{let o=Y.string();if(e.format){let i=e.format;if(i==="email")o=o.check(Y.email());else if(i==="uri"||i==="uri-reference")o=o.check(Y.url());else if(i==="uuid"||i==="guid")o=o.check(Y.uuid());else if(i==="date-time")o=o.check(Y.iso.datetime());else if(i==="date")o=o.check(Y.iso.date());else if(i==="time")o=o.check(Y.iso.time());else if(i==="duration")o=o.check(Y.iso.duration());else if(i==="ipv4")o=o.check(Y.ipv4());else if(i==="ipv6")o=o.check(Y.ipv6());else if(i==="mac")o=o.check(Y.mac());else if(i==="cidr")o=o.check(Y.cidrv4());else if(i==="cidr-v6")o=o.check(Y.cidrv6());else if(i==="base64")o=o.check(Y.base64());else if(i==="base64url")o=o.check(Y.base64url());else if(i==="e164")o=o.check(Y.e164());else if(i==="jwt")o=o.check(Y.jwt());else if(i==="emoji")o=o.check(Y.emoji());else if(i==="nanoid")o=o.check(Y.nanoid());else if(i==="cuid")o=o.check(Y.cuid());else if(i==="cuid2")o=o.check(Y.cuid2());else if(i==="ulid")o=o.check(Y.ulid());else if(i==="xid")o=o.check(Y.xid());else if(i==="ksuid")o=o.check(Y.ksuid())}if(typeof e.minLength==="number")o=o.min(e.minLength);if(typeof e.maxLength==="number")o=o.max(e.maxLength);if(e.pattern)o=o.regex(new RegExp(e.pattern));r=o;break}case"number":case"integer":{let o=n==="integer"?Y.number().int():Y.number();if(typeof e.minimum==="number")o=o.min(e.minimum);if(typeof e.maximum==="number")o=o.max(e.maximum);if(typeof e.exclusiveMinimum==="number")o=o.gt(e.exclusiveMinimum);else if(e.exclusiveMinimum===!0&&typeof e.minimum==="number")o=o.gt(e.minimum);if(typeof e.exclusiveMaximum==="number")o=o.lt(e.exclusiveMaximum);else if(e.exclusiveMaximum===!0&&typeof e.maximum==="number")o=o.lt(e.maximum);if(typeof e.multipleOf==="number")o=o.multipleOf(e.multipleOf);r=o;break}case"boolean":{r=Y.boolean();break}case"null":{r=Y.null();break}case"object":{let o={},i=e.properties||{},a=new Set(e.required||[]);for(let[c,l]of Object.entries(i)){let u=ct(l,t);o[c]=a.has(c)?u:u.optional()}if(e.propertyNames){let c=ct(e.propertyNames,t),l=e.additionalProperties&&typeof e.additionalProperties==="object"?ct(e.additionalProperties,t):Y.any();if(Object.keys(o).length===0){r=Y.record(c,l);break}let u=Y.object(o).passthrough(),d=Y.looseRecord(c,l);r=Y.intersection(u,d);break}if(e.patternProperties){let c=e.patternProperties,l=Object.keys(c),u=[];for(let p of l){let m=ct(c[p],t),b=Y.string().regex(new RegExp(p));u.push(Y.looseRecord(b,m))}let d=[];if(Object.keys(o).length>0)d.push(Y.object(o).passthrough());if(d.push(...u),d.length===0)r=Y.object({}).passthrough();else if(d.length===1)r=d[0];else{let p=Y.intersection(d[0],d[1]);for(let m=2;m<d.length;m++)p=Y.intersection(p,d[m]);r=p}break}let s=Y.object(o);if(e.additionalProperties===!1)r=s.strict();else if(typeof e.additionalProperties==="object")r=s.catchall(ct(e.additionalProperties,t));else r=s.passthrough();break}case"array":{let{prefixItems:o,items:i}=e;if(o&&Array.isArray(o)){let a=o.map((c)=>ct(c,t)),s=i&&typeof i==="object"&&!Array.isArray(i)?ct(i,t):void 0;if(s)r=Y.tuple(a).rest(s);else r=Y.tuple(a);if(typeof e.minItems==="number")r=r.check(Y.minLength(e.minItems));if(typeof e.maxItems==="number")r=r.check(Y.maxLength(e.maxItems))}else if(Array.isArray(i)){let a=i.map((c)=>ct(c,t)),s=e.additionalItems&&typeof e.additionalItems==="object"?ct(e.additionalItems,t):void 0;if(s)r=Y.tuple(a).rest(s);else r=Y.tuple(a);if(typeof e.minItems==="number")r=r.check(Y.minLength(e.minItems));if(typeof e.maxItems==="number")r=r.check(Y.maxLength(e.maxItems))}else if(i!==void 0){let a=ct(i,t),s=Y.array(a);if(typeof e.minItems==="number")s=s.min(e.minItems);if(typeof e.maxItems==="number")s=s.max(e.maxItems);r=s}else r=Y.array(Y.any());break}default:throw Error(`Unsupported type: ${n}`)}if(e.description)r=r.describe(e.description);if(e.default!==void 0)r=r.default(e.default);return r}function ct(e,t){if(typeof e==="boolean")return e?Y.any():Y.never();let n=QP(e,t),r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let s=e.anyOf.map((l)=>ct(l,t)),c=Y.union(s);n=r?Y.intersection(n,c):c}if(e.oneOf&&Array.isArray(e.oneOf)){let s=e.oneOf.map((l)=>ct(l,t)),c=Y.xor(s);n=r?Y.intersection(n,c):c}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)n=r?n:Y.any();else{let s=r?n:ct(e.allOf[0],t),c=r?0:1;for(let l=c;l<e.allOf.length;l++)s=Y.intersection(s,ct(e.allOf[l],t));n=s}if(e.nullable===!0&&t.version==="openapi-3.0")n=Y.nullable(n);if(e.readOnly===!0)n=Y.readonly(n);let o={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let s of i)if(s in e)o[s]=e[s];let a=["contentEncoding","contentMediaType","contentSchema"];for(let s of a)if(s in e)o[s]=e[s];for(let s of Object.keys(e))if(!oM.has(s))o[s]=e[s];if(Object.keys(o).length>0)t.registry.add(n,o);return n}function eO(e,t){if(typeof e==="boolean")return e?Y.any():Y.never();let n=rM(e,t?.defaultTarget),r=e.$defs||e.definitions||{},o={version:n,defs:r,refs:new Map,processing:new Set,rootSchema:e,registry:t?.registry??Xe};return ct(e,o)}var Y,oM;var tO=L(()=>{Oa();al();ja();Ea();Y={...Ra,...il,iso:Kr},oM=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"])});var ab={};hn(ab,{bigint:()=>lM,boolean:()=>cM,date:()=>uM,number:()=>sM,string:()=>aM});function aM(e){return Oh(Wr,e)}function sM(e){return Lh(Hr,e)}function cM(e){return Fh(Zr,e)}function lM(e){return Gh(Jr,e)}function uM(e){return ef(Ua,e)}var nO=L(()=>{Dt();Ea()});var k={};hn(k,{$brand:()=>ip,$input:()=>wh,$output:()=>kh,NEVER:()=>rp,TimePrecision:()=>Ah,ZodAny:()=>Iy,ZodArray:()=>Py,ZodBase64:()=>Ol,ZodBase64URL:()=>xl,ZodBigInt:()=>Jr,ZodBigIntFormat:()=>_l,ZodBoolean:()=>Zr,ZodCIDRv4:()=>Cl,ZodCIDRv6:()=>Pl,ZodCUID:()=>yl,ZodCUID2:()=>bl,ZodCatch:()=>Vy,ZodCodec:()=>Nl,ZodCustom:()=>Ka,ZodCustomStringFormat:()=>Vr,ZodDate:()=>Ua,ZodDefault:()=>Fy,ZodDiscriminatedUnion:()=>xy,ZodE164:()=>Al,ZodEmail:()=>gl,ZodEmoji:()=>hl,ZodEnum:()=>qr,ZodError:()=>XU,ZodExactOptional:()=>Ny,ZodFile:()=>Dy,ZodFirstPartyTypeKind:()=>ib,ZodFunction:()=>nb,ZodGUID:()=>La,ZodIPv4:()=>kl,ZodIPv6:()=>wl,ZodISODate:()=>cl,ZodISODateTime:()=>sl,ZodISODuration:()=>ul,ZodISOTime:()=>ll,ZodIntersection:()=>Ay,ZodIssueCode:()=>eM,ZodJWT:()=>Tl,ZodKSUID:()=>Il,ZodLazy:()=>Qy,ZodLiteral:()=>zy,ZodMAC:()=>gy,ZodMap:()=>Ey,ZodNaN:()=>Zy,ZodNanoID:()=>fl,ZodNever:()=>wy,ZodNonOptional:()=>Dl,ZodNull:()=>vy,ZodNullable:()=>My,ZodNumber:()=>Hr,ZodNumberFormat:()=>Go,ZodObject:()=>Fa,ZodOptional:()=>zl,ZodPipe:()=>$l,ZodPrefault:()=>Gy,ZodPromise:()=>tb,ZodReadonly:()=>Jy,ZodRealError:()=>Ct,ZodRecord:()=>Ga,ZodSet:()=>Ly,ZodString:()=>Wr,ZodStringFormat:()=>Te,ZodSuccess:()=>Wy,ZodSymbol:()=>yy,ZodTemplateLiteral:()=>Xy,ZodTransform:()=>$y,ZodTuple:()=>_y,ZodType:()=>fe,ZodULID:()=>vl,ZodURL:()=>Na,ZodUUID:()=>kn,ZodUndefined:()=>by,ZodUnion:()=>Ba,ZodUnknown:()=>ky,ZodVoid:()=>Cy,ZodXID:()=>Sl,ZodXor:()=>Oy,_ZodString:()=>ml,_default:()=>By,_function:()=>GP,any:()=>IP,array:()=>Ma,base64:()=>rP,base64url:()=>iP,bigint:()=>fP,boolean:()=>fy,catch:()=>Hy,check:()=>KP,cidrv4:()=>nP,cidrv6:()=>oP,clone:()=>ft,codec:()=>MP,coerce:()=>ab,config:()=>$e,core:()=>Nn,cuid:()=>HC,cuid2:()=>ZC,custom:()=>qP,date:()=>wP,decode:()=>ay,decodeAsync:()=>cy,describe:()=>WP,discriminatedUnion:()=>TP,e164:()=>aP,email:()=>NC,emoji:()=>WC,encode:()=>iy,encodeAsync:()=>sy,endsWith:()=>zr,enum:()=>El,exactOptional:()=>Uy,file:()=>DP,flattenError:()=>ma,float32:()=>pP,float64:()=>mP,formatError:()=>ga,fromJSONSchema:()=>eO,function:()=>GP,getErrorMap:()=>nM,globalRegistry:()=>Xe,gt:()=>Sn,gte:()=>yt,guid:()=>UC,hash:()=>dP,hex:()=>uP,hostname:()=>lP,httpUrl:()=>qC,includes:()=>Er,instanceof:()=>HP,int:()=>pl,int32:()=>gP,int64:()=>yP,intersection:()=>Ty,ipv4:()=>QC,ipv6:()=>tP,iso:()=>Kr,json:()=>JP,jwt:()=>sP,keyof:()=>CP,ksuid:()=>XC,lazy:()=>eb,length:()=>Fo,literal:()=>zP,locales:()=>Pa,looseObject:()=>xP,looseRecord:()=>jP,lowercase:()=>jr,lt:()=>vn,lte:()=>zt,mac:()=>eP,map:()=>RP,maxLength:()=>Mo,maxSize:()=>io,meta:()=>VP,mime:()=>Dr,minLength:()=>$n,minSize:()=>In,multipleOf:()=>ro,nan:()=>UP,nanoid:()=>VC,nativeEnum:()=>LP,negative:()=>Yc,never:()=>jl,nonnegative:()=>Qc,nonoptional:()=>qy,nonpositive:()=>Xc,normalize:()=>$r,null:()=>Sy,nullable:()=>Da,nullish:()=>$P,number:()=>hy,object:()=>PP,optional:()=>za,overwrite:()=>nn,parse:()=>ty,parseAsync:()=>ny,partialRecord:()=>_P,pipe:()=>$a,positive:()=>Jc,prefault:()=>Ky,preprocess:()=>YP,prettifyError:()=>fp,promise:()=>BP,property:()=>el,readonly:()=>Yy,record:()=>Ry,refine:()=>ob,regex:()=>_r,regexes:()=>Vt,registry:()=>Tc,safeDecode:()=>uy,safeDecodeAsync:()=>py,safeEncode:()=>ly,safeEncodeAsync:()=>dy,safeParse:()=>oy,safeParseAsync:()=>ry,set:()=>EP,setErrorMap:()=>tM,size:()=>Uo,slugify:()=>Fr,startsWith:()=>Lr,strictObject:()=>OP,string:()=>dl,stringFormat:()=>cP,stringbool:()=>ZP,success:()=>NP,superRefine:()=>rb,symbol:()=>vP,templateLiteral:()=>FP,toJSONSchema:()=>rl,toLowerCase:()=>Ur,toUpperCase:()=>Mr,transform:()=>Ll,treeifyError:()=>hp,trim:()=>Nr,tuple:()=>jy,uint32:()=>hP,uint64:()=>bP,ulid:()=>JC,undefined:()=>SP,union:()=>Rl,unknown:()=>Bo,uppercase:()=>Rr,url:()=>KC,util:()=>G,uuid:()=>MC,uuidv4:()=>FC,uuidv6:()=>BC,uuidv7:()=>GC,void:()=>kP,xid:()=>YC,xor:()=>AP});var sb=L(()=>{Dt();Dt();Lg();Dt();_a();tO();Ih();ja();ja();nO();Ea();al();ey();my();XP();$e(Ia())});var lt=L(()=>{sb();sb()});var oO,rO,iO,aO,sO,cO,lO,uO,dO,pO,mO,gO,hO,cb,dM,lb,fO,pM,ub="cursor",db="GET",pb="control",mb="[DONE]";var yO=L(()=>{lt();oO=k.object({type:k.literal("run_started"),runId:k.string().describe("Server-assigned run ID for the started run.")}),rO=k.object({type:k.literal("message_started"),messageId:k.string().describe("Server-assigned assistant message ID for this run.")}),iO=k.object({type:k.literal("text_chunk"),messageId:k.string().describe("Assistant message the chunk belongs to."),content:k.string().describe("Incremental text delta to append.")}),aO=k.object({type:k.literal("text_complete"),messageId:k.string().describe("Assistant message that completed."),content:k.string().describe("Full assistant text for the message.")}),sO=k.object({type:k.literal("reasoning_progress"),messageId:k.string().describe("Assistant message the progress belongs to."),estimatedTokens:k.number().int().nonnegative().describe("Cumulative estimate for the current thinking block.")}),cO=k.object({type:k.literal("reasoning_complete"),messageId:k.string().describe("Assistant message that completed.")}),lO=k.object({type:k.literal("tool_call_pending"),toolCallId:k.string().describe("Stable identifier for the tool call."),name:k.string().describe("Name of the tool being called.")}),uO=k.object({type:k.literal("tool_call_start"),toolCallId:k.string().describe("Stable identifier for the tool call."),name:k.string().describe("Name of the tool being called."),params:k.unknown().describe("Resolved tool input params.")}),dO=k.object({type:k.literal("tool_call_complete"),toolCallId:k.string().describe("Stable identifier for the tool call."),status:k.enum(["in_progress","success","error"]).describe("Terminal (or transitional) status of the tool call."),result:k.unknown().optional().describe("Tool output, when available."),durationMs:k.number().nonnegative().optional().describe("Authoritative server-measured tool execution time in ms.")}),pO=k.object({type:k.literal("artifact"),name:k.string().describe("Artifact kind (for example table, timeseries)."),data:k.unknown().describe("Artifact payload; shape depends on name."),toolCallId:k.string().describe("Tool call that produced the artifact.")}),mO=k.object({type:k.literal("error"),message:k.string().describe("Human-readable error message."),name:k.string().optional().describe("Optional error class/name.")}),gO=k.object({type:k.literal("stream_reset"),messageId:k.string().describe("Assistant message whose content to reset.")}),hO=k.object({type:k.literal("disconnected")}),cb=k.discriminatedUnion("type",[oO,rO,iO,aO,sO,cO,lO,uO,dO,pO,mO,gO,hO]),dM=k.enum(["run_started","message_started","text_chunk","text_complete","reasoning_progress","reasoning_complete","tool_call_pending","tool_call_start","tool_call_complete","artifact","error","stream_reset","disconnected"]),lb=k.object({streamNextOffset:k.string().describe("Opaque resume cursor for the next unread event; pass back as the stream 'cursor' query param.")}),fO=k.string().describe("Opaque resume cursor from a prior control frame's streamNextOffset."),pM=k.object({cursor:fO.optional().describe("Resume the stream after this offset. Omit to start from the beginning of the retained buffer.")})});var Ko=2000,mM;var bO=L(()=>{mM=`description must be at most ${2000 .toLocaleString()} characters.`});var gb;var vO=L(()=>{gb=["github","google","microsoft","linear","bitbucket","slack"]});var Ul,hb;var SO=L(()=>{lt();Ul=k.object({projectId:k.string().uuid().optional().describe("Project to create the issue in. Auto-filled from CLI and SDK context when omitted."),name:k.string().trim().min(1).optional().describe('Stable issue name for indexing and mute matching: at most 80 characters, plain English, in the form "<service or surface>: <customer-visible symptom>", without counts, timestamps, or internal identifiers. When omitted, the name is derived from contentMdx.'),contentMdx:k.string().trim().min(1,"contentMdx cannot be empty").optional().describe("One message for the customer's engineer, posted to Slack as written. No headings or section labels. Say each fact once: what broke, for whom, since when, and whether it is still happening; the cause, or one clause that no deploy in the window explains it and then the mechanism; the counts and times; the decision; one short snippet only where the code is the proof. At most 320 words outside code and 3000 characters after Slack formatting. No line may start with a section label such as Summary:. No Sazabi identifiers. Required unless sample is true."),severity:k.enum(["low","medium","high","critical"]).default("medium").describe("Issue severity used for prioritization and triage."),componentId:k.string().uuid().optional().describe("UUID of a registered component this issue belongs to. Required unless sample is true: every issue must be attributed to a component. List components first and pick the best match; register one if none fits. Missing or unknown IDs are rejected."),statusStartedAt:k.string().datetime({offset:!0}).optional().describe("Optional ISO timestamp for when the linked status-page incident began."),suspectedPullRequest:k.object({provider:k.enum(["github","bitbucket"]).default("github").describe("Forge hosting the pull request. Defaults to GitHub for legacy callers."),repositoryFullName:k.string().trim().min(1).max(240).regex(/^[^/\s]+\/[^/\s]+$/,"Use owner/repo format."),number:k.number().int().positive()}).optional().describe("Optional pull request that the agent suspects caused this issue. It must be an agent-created PR in this project."),sample:k.boolean().optional().describe("Deprecated (ENG-7347): the sample-issue onboarding step is a static exhibit and no longer creates an issue. Kept as a compat shim for @sazabi/cli <= 1.7.0 — the server marks the onboarding sample-issue step complete and returns a synthetic non-persisted issue snapshot. Mutually exclusive with the content inputs (name, contentMdx, severity, componentId, statusStartedAt); projectId stays allowed. Requires a user credential.")}),hb=Ul.superRefine((e,t)=>{if(e.sample){let n=[["name",e.name!==void 0],["contentMdx",e.contentMdx!==void 0],["severity",e.severity!=="medium"],["componentId",e.componentId!==void 0],["statusStartedAt",e.statusStartedAt!==void 0]];for(let[r,o]of n)if(o)t.addIssue({code:"custom",path:[r],message:`${r} is not allowed when sample is true.`})}else{if(!e.contentMdx)t.addIssue({code:"custom",path:["contentMdx"],message:"contentMdx is required"});if(!e.componentId)t.addIssue({code:"custom",path:["componentId"],message:"componentId is required"})}if(e.statusStartedAt&&!e.componentId)t.addIssue({code:"custom",path:["statusStartedAt"],message:"statusStartedAt requires componentId."})})});var IO,gM,hM=1e4,kO;var wO=L(()=>{lt();IO=["series","table","evidence"],gM=["other","drop"],kO=k.strictObject({limit:k.number().int().positive().max(hM),overflow:k.enum(gM)})});var Oee;var CO=L(()=>{lt();Oee=k.looseObject({kind:k.string().min(1)})});var fM,yM,bM=5000,vM=32,PO=(e)=>k.discriminatedUnion("op",[k.strictObject({op:k.literal("count")}),k.strictObject({op:k.literal("event_rate")}),k.strictObject({op:k.literal("distinct"),field:e}),k.strictObject({op:k.literal("numeric"),field:e,parseAs:k.literal("float64"),aggregate:k.enum(fM),invalidValues:k.enum(["drop","error"])}),k.strictObject({op:k.literal("recent_rows"),limit:k.number().int().positive().max(bM),fields:k.array(e).max(vM).optional(),order:k.enum(yM).optional()})]);var OO=L(()=>{lt();fM=["sum","avg","min","max","p50","p95","p99"],yM=["newest","oldest"]});var SM,Ml=100,IM=8192,xO,kM,wM=(e,t)=>{if(e==="exists")return t===void 0?void 0:"exists takes no value";if(t===void 0)return`${e} requires a value`;if(e==="in"){if(!Array.isArray(t))return"in requires an array value";if(t.length>Ml)return`in accepts at most ${Ml} values`}return},fb=50,AO=8,TO=200,_O=65536,CM=(e)=>{if(typeof e==="string")return e.length;if(!Array.isArray(e))return 0;let t=0;for(let n of e)if(typeof n==="string")t+=n.length;return t},PM=(e)=>{let t=0,n=0,r=[{node:e,depth:1}];for(let o=r.pop();o!==void 0;o=r.pop()){if(t+=1,t>TO)return`predicate has more than ${TO} nodes`;if(o.depth>AO)return`predicate nests deeper than ${AO} levels`;if(typeof o.node!=="object"||o.node===null)continue;let{children:i,child:a,value:s}=o.node;if(n+=CM(s),n>_O)return`predicate operands exceed ${_O} characters in total`;if(Array.isArray(i)){if(i.length>fb)return`predicate has a node with more than ${fb} children`;for(let c of i)r.push({node:c,depth:o.depth+1})}if(a!==void 0)r.push({node:a,depth:o.depth+1})}return},jO=(e)=>{let t=k.lazy(()=>k.discriminatedUnion("op",[k.strictObject({op:k.enum(["and","or"]),children:k.array(t).max(fb)}),k.strictObject({op:k.literal("not"),child:t}),k.strictObject({op:k.literal("compare"),field:e,comparator:k.enum(SM),value:kM.optional()}).superRefine((n,r)=>{let o=wM(n.comparator,n.value);if(o)r.addIssue({code:"custom",path:["value"],message:o})})]));return k.unknown().superRefine((n,r)=>{let o=PM(n);if(o)r.addIssue({code:"custom",message:o})}).pipe(t)};var RO=L(()=>{lt();SM=["eq","neq","gt","gte","lt","lte","in","contains","starts_with","exists"],xO=k.union([k.string().max(IM),k.number(),k.boolean(),k.null()]),kM=k.union([xO,k.array(xO).max(Ml,{error:`in accepts at most ${Ml} values`})])});var yb=L(()=>{wO();CO();OO();RO()});var Fl,OM,EO,xM,AM=0.95,TM,_M,jM,RM,EM,LM,Nee,Uee;var LO=L(()=>{lt();Fl=k.iso.datetime({offset:!0}),OM=["request_metrics","event_volume","pattern_volume","log_volume","standing","pattern_index","exact_scan","sampled_scan"],EO=k.enum(OM),xM=["exact","approximate"],TM=["tdigest","reservoir_sample"],_M=["coarsen_bucket","narrow_window","allow_approximation","promote_attribute"],jM=k.enum(_M),RM=k.discriminatedUnion("kind",[k.strictObject({kind:k.literal("sampling"),relativeBound:k.number().nonnegative(),confidence:k.literal(AM),sampleFraction:k.number().gt(0).lte(1),cellRows:k.number().nonnegative(),minCellRows:k.number().int().positive(),designEffect:k.number().min(1),omissionProbability:k.strictObject({oneIdentity:k.number().min(0).max(1),boundedCell:k.number().min(0).max(1),boundedCellIdentities:k.number().min(1),maxMultiplicity:k.number().min(1).nullable(),basis:k.string().min(1)})}),k.strictObject({kind:k.literal("quantile_sketch"),algorithm:k.enum(TM),compression:k.number().positive()}),k.strictObject({kind:k.literal("distinct_sketch"),algorithm:k.string().min(1)})]),EM=["stored_range","request_columns","read_limit"],LM=k.strictObject({rows:k.number().nonnegative(),bytes:k.number().nonnegative()}),Nee=k.strictObject({representation:EO,exactness:k.enum(xM),error:RM.optional(),estimate:LM.optional(),coverage:k.strictObject({from:Fl,to:Fl,status:k.enum(["complete","partial"]),reason:k.enum(EM).optional()}),freshness:k.strictObject({watermark:Fl,openBucketFrom:Fl.optional()}),catalogRevision:k.string().regex(/^\d+$/).optional(),population:k.strictObject({kind:k.literal("services"),services:k.array(k.string().min(1)).min(1),unmatchedRows:k.number().int().nonnegative().nullable()}).optional()}).refine((e)=>e.exactness==="approximate"===(e.error!==void 0),{path:["error"],message:"error is required exactly when exactness is approximate"}),Uee=k.strictObject({representation:EO,reason:k.string().min(1),suggestion:jM.optional()})});var bb,zM,DM,vb,$M,NM,UM,MM,Sb;var zO=L(()=>{lt();yb();bb=k.string().trim().min(1).max(1024),zM=k.enum(["resource","scope","log"]),DM=k.strictObject({kind:k.literal("body_json"),path:k.array(bb).min(1).max(8)}),vb=k.discriminatedUnion("kind",[k.strictObject({kind:k.literal("service")}),k.strictObject({kind:k.literal("severity_number")}),k.strictObject({kind:k.literal("column"),name:bb}),k.strictObject({kind:k.literal("attribute"),source:zM,key:bb}),k.strictObject({kind:k.literal("body")}),k.strictObject({kind:k.literal("message")}),DM]),$M=jO(vb),NM=["sum","avg","max","p50","p95","p99"],UM=k.discriminatedUnion("op",[...PO(vb).options,k.strictObject({op:k.literal("error_count")}),k.strictObject({op:k.literal("duration"),aggregate:k.enum(NM)})]),MM=["1m","5m","1h","1d"],Sb=k.strictObject({version:k.literal(2),source:k.strictObject({kind:k.literal("logs")}),predicate:$M,dimensions:k.array(vb).max(3),measure:UM,bucket:k.enum(MM).optional(),output:k.enum(IO),series:kO.optional(),exactness:k.enum(["exact","approximate_ok"]),approximation:k.strictObject({maxRelativeError:k.number().gt(0).lte(1)}).optional()}).refine((e)=>e.exactness==="approximate_ok"===(e.approximation!==void 0),{path:["approximation"],message:"approximation is required exactly when exactness is approximate_ok"}).refine((e)=>e.output==="evidence"===(e.measure.op==="recent_rows"),{path:["output"],message:"evidence output carries the recent_rows measure, and only that"})});var Bl,FM=7776000,qee,Wee,BM=60000,GM,Vee;var DO=L(()=>{lt();Bl=k.iso.datetime({offset:!0}),qee=k.discriminatedUnion("kind",[k.strictObject({kind:k.literal("absolute"),from:Bl,to:Bl}).refine(({from:e,to:t})=>Date.parse(e)<Date.parse(t),{message:"absolute time range must have from before to"}),k.strictObject({kind:k.literal("relative"),lookbackSeconds:k.number().int().positive().max(FM)})]),Wee=k.strictObject({from:Bl,to:Bl}).refine(({from:e,to:t})=>Date.parse(e)<Date.parse(t),{message:"resolved time range must have from before to"}),GM=60*BM,Vee=24*GM});var $O=L(()=>{yb();LO();zO();DO()});var NO,UO,MO,KM,qM="Kind filter must be a comma-separated list of note, runbook, or change.",WM=(e,t)=>{let n=e.split(",").map((o)=>o.trim()).filter(Boolean),r=k.array(MO).min(1).safeParse(n);if(!r.success)return t.addIssue({code:"custom",message:qM}),k.NEVER;return r.data},Ib;var FO=L(()=>{lt();NO=["note","runbook"],UO=["note","runbook","change"],MO=k.enum(UO),KM=k.enum(NO),Ib=k.string().min(1).transform(WM).describe("Comma-separated kinds, for example note,runbook.")});var Yr;var BO=L(()=>{lt();Yr=k.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"])});var kb=(e)=>({completed:!1,threadId:e.threadId,runId:e.runId,...e.messageId!==void 0?{messageId:e.messageId}:{},status:"processing",response:null,failureClass:null,failureRetryable:null});var wn=L(()=>{yO();bO();vO();SO();$O();FO();BO()});var VM="https://api.sazabi.com",HM="x-sazabi-client-source",ZM="x-sazabi-client-version",KO=(e)=>({streamRun:async(t)=>GO({options:e,path:`/runs/${encodeURIComponent(t.runId)}/stream`,cursor:t.cursor,signal:t.signal}),streamThread:async(t)=>GO({options:e,path:`/threads/${encodeURIComponent(t.threadId)}/stream`,cursor:t.cursor,signal:t.signal})}),GO=async(e)=>{let t=e.options.fetch??globalThis.fetch;if(!t)throw Error("Fetch transport is not available in this runtime.");let n=await e.options.credentialProvider.getToken(),r=JM(e.options.apiBaseUrl,e.path,e.cursor);return XM({url:r,token:n,clientSource:e.options.clientSource,clientVersion:e.options.clientVersion,initialCursor:e.cursor,signal:e.signal,fetch:t})},JM=(e,t,n)=>{let r=YM(e??VM),o=new URL(`${r}${t}`);if(n)o.searchParams.set(ub,n);return o.toString()},YM=(e)=>{let t=e.replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`},XM=async(e)=>{let t=[],n=[],r=!1,o=!1,i,a=e.initialCursor,s=new AbortController,c=(y)=>{if(r)return;r=!0,i=y;while(n.length>0)n.shift()?.({value:void 0,done:!0})},l=(y)=>{let I=n.shift();if(I){I({value:y,done:!1});return}t.push(y)},u=(y)=>{if(y.event===pb){let C=o0(y.data);if(C!==void 0)a=C;return}if(y.data===mb){o=!0,s.abort(),c();return}let I=r0(y.data);if(I)l(I)},d=()=>{o=!0,s.abort(),c()};if(e.signal)if(e.signal.aborted)o=!0,s.abort();else e.signal.addEventListener("abort",d,{once:!0});let p={[Symbol.asyncIterator](){return p},get cursor(){return a},next:async()=>{if(t.length>0)return{value:t.shift(),done:!1};if(r){if(i)throw i;return{value:void 0,done:!0}}return new Promise((y)=>{n.push(y)}).then((y)=>{if(y.done&&i)throw i;return y})},return:async()=>(o=!0,s.abort(),c(),{value:void 0,done:!0}),throw:async(y)=>{throw o=!0,s.abort(),c(y instanceof Error?y:Error(String(y))),y},close:async()=>{o=!0,s.abort(),c()}};if(o)return c(),p;let m=await e.fetch(e.url,{method:db,headers:QM(e.token,e.clientSource,e.clientVersion),signal:s.signal});if(await e0(m))c();else t0(m,u).then(()=>c()).catch((y)=>{if(a0(y)||o||e.signal?.aborted){c();return}c(s0(y))});return p},QM=(e,t,n)=>({accept:"text/event-stream",authorization:`Bearer ${e}`,...t?{[HM]:t}:{},...n?{[ZM]:n}:{}}),e0=async(e)=>{if(e.status===204)return!0;if(e.ok&&e.body)return!1;let t=await i0(e);if(e.status===401)throw Error("Authentication failed. Check your credential.");if(e.status===403)throw Error(`Forbidden (403): ${t||"Credential may not have access to this resource"}`);if(e.status===404)throw Error(`Not found (404): ${t||"Run or thread not found"}`);if(e.status===400)throw Error(`Invalid stream cursor (400): ${t||"The provided cursor was rejected"}`);if(e.status>=400&&e.status<500&&e.status!==429)throw Error(`Client error (${e.status}): ${t}`);if(!e.body)throw Error("Agent stream response did not include a body.");throw Error(e.status===429?`Rate limited (429): ${t}`:`Server error (${e.status}): ${t}`)},t0=async(e,t)=>{let n=e.body?.getReader();if(!n)throw Error("Agent stream response did not include a body.");let r=new TextDecoder,o="",i=n0(t);try{while(!0){let a=await n.read();if(a.done)break;o+=r.decode(a.value,{stream:!0});let s=o.split(/\r\n|\r|\n/);o=s.pop()??"";for(let c of s)i.line(c)}if(o+=r.decode(),o)for(let a of o.split(/\r\n|\r|\n/))i.line(a);i.flush()}finally{n.releaseLock()}},n0=(e)=>{let t="message",n=[],r=()=>{t="message",n=[]},o=()=>{if(n.length===0){r();return}e({event:t,data:n.join(`
|
|
115
115
|
`)}),r()};return{line:(i)=>{if(i===""){o();return}if(i.startsWith(":"))return;let a=i.indexOf(":"),s=a===-1?i:i.slice(0,a),c=a===-1?"":i.slice(a+1),l=c.startsWith(" ")?c.slice(1):c;if(s==="event"){t=l||"message";return}if(s==="data")n.push(l)},flush:o}},o0=(e)=>{try{let t=lb.safeParse(JSON.parse(e));return t.success?t.data.streamNextOffset:void 0}catch{return}},r0=(e)=>{try{let t=cb.safeParse(JSON.parse(e));return t.success?t.data:void 0}catch{return}},i0=async(e)=>{try{return await e.text()}catch{return""}},a0=(e)=>e instanceof Error&&e.name==="AbortError",s0=(e)=>e instanceof Error?e:Error(String(e));var qO=L(()=>{wn()});var wb,Cb,Pb,WO;var VO=L(()=>{lt();wb=k.object({severities:k.array(k.string()).optional().describe("Limit results to the listed severities."),services:k.array(k.string()).optional().describe("Limit results to the listed service names."),environments:k.array(k.string()).optional().describe("Limit results to the listed deployment environments."),searchTerm:k.string().optional().describe("Case-insensitive substring match against the log body."),traceId:k.string().optional().describe("Limit results to one trace ID."),attributes:k.record(k.string(),k.string()).optional().describe("Limit results to logs whose attributes contain every listed key with an exactly equal value.")}),Cb=k.object({service:k.string(),namespace:k.string(),environment:k.string(),host:k.string(),container:k.string(),pod:k.string()}),Pb=k.object({id:k.string(),timestamp:k.string().datetime(),severity:k.string(),body:k.string(),service:k.string(),traceId:k.string(),spanId:k.string(),attributes:k.record(k.string(),k.string()),resource:Cb}),WO=k.object({type:k.literal("logs"),timestamp:k.string().datetime(),data:k.array(Pb)})});var c0="https://{region}.intake.sazabi.com",l0="https://{region}.tail.sazabi.com",JO=500,u0=5000,YO="sazabi.public_key",d0="x-sazabi-internal-log-forwarding-secret",p0="x-sazabi-internal-log-forwarding-source",m0=(e)=>e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,XO=(e)=>{let t=m0(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"},g0,h0,f0,QO=(e)=>{let t=new Map;return{tail:async(n)=>{let r=await A0(e.credentialProvider,n.projectId,"logs.tail"),o=await T0(e,t,r,n.region,"logs.tail"),i=v0({projectId:r,region:o,filters:n.filters,apiBaseUrl:e.apiBaseUrl,tailBaseUrl:e.tailBaseUrl}),a=await e.credentialProvider.getToken(),s=e.fetch??globalThis.fetch;if(!s)throw Error("Fetch transport is not available in this runtime.");return j0({token:a,url:i,signal:n.signal,fetch:s})},forward:async(n)=>{let r=await _0(e,t,n.projectId??await e.credentialProvider.getProjectId?.(),n.region,"logs.forward"),o=w0(r,e.intakeBaseUrl),i=e.fetch??globalThis.fetch,a=P0(n.logs,n.publicKey),s=U0(a);return await N0(i,o,a,x0(n.sazabiInternalForwarding)),{forwardedCount:s,failedCount:0}}}},y0="3010",b0,v0=(e)=>{let t=(e.tailBaseUrl??S0({region:e.region,apiBaseUrl:e.apiBaseUrl})).replace("{region}",e.region),n=I0(t);n.searchParams.set("projectId",e.projectId);let r=k0(e.filters);if(r)n.searchParams.set("filters",r);return n.toString()},S0=(e)=>{if(e.apiBaseUrl)try{let t=new URL(e.apiBaseUrl).hostname;if(t.endsWith(".sazabi.dev")){let n=t.includes(".staging.")?"staging.sazabi.dev":"development.sazabi.dev";return`https://${e.region}.tail.${n}`}}catch{}return l0.replace("{region}",e.region)},I0=(e)=>{let t=(()=>{try{return new URL(e)}catch{return null}})();if(!t)throw Error(`Invalid tail base URL: ${e}`);if(XO(t.hostname)){if(t.protocol="http:",!t.port||b0.has(t.port))t.port=y0;return t.pathname="/v1/tail",t.search="",t.hash="",t}if(t.protocol==="ws:"||t.protocol==="wss:")t.protocol=t.protocol==="wss:"?"https:":"http:";if(t.protocol!=="http:"&&t.protocol!=="https:")throw Error(`Invalid tail base URL protocol: ${t.protocol}. Expected http:, https:, ws:, or wss:.`);return t.pathname="/v1/tail",t.search="",t.hash="",t},k0=(e)=>{if(!e)return;let t=Object.entries(e).filter(([,n])=>n!==void 0&&(!Array.isArray(n)||n.length>0)&&(typeof n!=="object"||Array.isArray(n)||n===null||Object.keys(n).length>0)&&n!=="");if(t.length===0)return;return JSON.stringify(Object.fromEntries(t))},w0=(e,t)=>{let n=(t??c0).replace("{region}",e),r=n.endsWith("/")?n.slice(0,-1):n,o=C0(r);if(o)return o;let i=r.match(/^https:\/\/([a-z0-9-]+)\.intake\.([a-z0-9.]+)$/);return`${i?`https://otlp.${i[1]}.intake.${i[2]}`:r}/v1/logs`},C0=(e)=>{let t=(()=>{try{return new URL(e)}catch{return null}})();if(!t)return;if(!XO(t.hostname))return;return t.pathname="/adapters/otlp",t.toString()},P0=(e,t)=>{let n=e.resourceLogs;if(!n||n.length===0)return{...e,resourceLogs:[{resource:{attributes:[ex(t)]},scopeLogs:[]}]};return{...e,resourceLogs:n.map((r)=>({...r,resource:{...r.resource,attributes:O0(r.resource?.attributes,t)}}))}},O0=(e,t)=>[...(e??[]).filter((r)=>r?.key!==YO),ex(t)],ex=(e)=>({key:YO,value:{stringValue:e}}),x0=(e)=>{if(!e?.secret)return{};return{[d0]:e.secret,...e.source?{[p0]:e.source}:{}}},A0=async(e,t,n)=>{let r=t??await e.getProjectId?.();if(r)return r;throw ox(n,"Project ID is required",["projectId"])},T0=async(e,t,n,r,o)=>r??await tx(e,t,n),_0=async(e,t,n,r,o)=>{if(r)return r;if(!n)throw ox(o,"Project ID is required",["projectId"]);return tx(e,t,n)},tx=async(e,t,n)=>{let r=t.get(n);if(r)return r;let o=e.raw.projects.get({projectId:n}).then((i)=>i.project.region);t.set(n,o);try{return await o}catch(i){throw t.delete(n),i}},j0=async(e)=>{let t=[],n=[],r=!1,o=!1,i,a=0,s,c,l=(I)=>{if(r)return;r=!0,i=I;while(n.length>0){let C=n.shift();if(C)C({value:void 0,done:!0})}},u=(I)=>{let C=n.shift();if(C){C({value:I,done:!1});return}t.push(I)},d=()=>{c?.abort()},p=(I)=>{if(I.event!=="log"){if(I.id)s=I.id;return}let C=D0(I.data);for(let B of C)u(B);if(I.id)s=I.id},m=async(I)=>{let C=!1;while(!r&&!o){let B=new AbortController,V=()=>B.abort();c=B;let ee=!1;e.signal?.addEventListener("abort",V,{once:!0});try{let Z=await e.fetch(R0(e.url,s),{method:"GET",headers:{accept:"text/event-stream",authorization:`Bearer ${e.token}`},signal:B.signal});await E0(Z),a=0,C=!0,I(),await L0(Z,p),ee=!0}catch(Z){if(ZO(Z)||e.signal?.aborted)break;let re=HO(Z);if(!C||$0(re))throw re;ee=!0}finally{if(e.signal?.removeEventListener("abort",V),c===B)c=void 0}if(r||o||e.signal?.aborted)break;if(!ee)continue;a+=1,await nx(Math.min(JO*2**(a-1),u0),e.signal)}};if(e.signal?.addEventListener("abort",()=>{o=!0,d(),l()},{once:!0}),e.signal?.aborted)o=!0,d(),l();await new Promise((I,C)=>{let B=!1;m(()=>{if(!B)B=!0,I()}).catch((ee)=>{let Z=HO(ee);if(!B){B=!0,C(Z);return}if(!ZO(ee))l(Z)})});let y={[Symbol.asyncIterator](){return y},next:async()=>{if(t.length>0)return{value:t.shift(),done:!1};if(r){if(i)throw i;return{value:void 0,done:!0}}return new Promise((I)=>{n.push(I)}).then((I)=>{if(I.done&&i)throw i;return I})},return:async()=>(o=!0,d(),l(),{value:void 0,done:!0}),throw:async(I)=>{throw o=!0,d(),l(I instanceof Error?I:Error(String(I))),I}};return y},R0=(e,t)=>{if(!t)return e;let n=new URL(e);return n.searchParams.set("cursor",t),n.toString()},E0=async(e)=>{if(e.ok&&e.body)return;let t=await e.text();if(e.status===401)throw Error("Authentication failed. Check your credential.");if(e.status===403){if(/not served by this region/i.test(t))throw Error(`Wrong region (403): ${t||"Project is not served by this region"}`);throw Error(`Forbidden (403): ${t||"Credential may not have access to this project"}`)}if(e.status>=400&&e.status<500&&e.status!==429)throw Error(`Client error (${e.status}): ${t}`);if(!e.body)throw Error("Tail stream response did not include a body.");throw Error(e.status===429?`Rate limited (429): ${t}`:`Server error (${e.status}): ${t}`)},L0=async(e,t)=>{let n=e.body?.getReader();if(!n)throw Error("Tail stream response did not include a body.");let r=new TextDecoder,o="",i=z0(t);try{while(!0){let a=await n.read();if(a.done)break;o+=r.decode(a.value,{stream:!0});let s=o.split(/\r\n|\r|\n/);o=s.pop()??"";for(let c of s)i.line(c)}if(o+=r.decode(),o){let a=o.split(/\r\n|\r|\n/);for(let s of a)i.line(s)}i.flush()}finally{n.releaseLock()}},z0=(e)=>{let t="message",n,r=[],o=()=>{t="message",n=void 0,r=[]},i=()=>{if(r.length===0&&!n){o();return}e({event:t,data:r.join(`
|
|
116
|
-
`),...n?{id:n}:{}}),o()};return{line:(a)=>{if(a===""){i();return}if(a.startsWith(":"))return;let s=a.indexOf(":"),c=s===-1?a:a.slice(0,s),l=s===-1?"":a.slice(s+1),u=l.startsWith(" ")?l.slice(1):l;if(c==="event"){t=u||"message";return}if(c==="data"){r.push(u);return}if(c==="id"&&!u.includes("\x00"))n=u},flush:i}},D0=(e)=>{try{let t=WO.safeParse(JSON.parse(e));if(!t.success)return[];return t.data.data}catch{return[]}},HO=(e)=>e instanceof Error?e:Error(String(e)),ZO=(e)=>e instanceof Error&&e.name==="AbortError",$0=(e)=>e.message.startsWith("Authentication failed")||e.message.startsWith("Forbidden (")||e.message.startsWith("Wrong region (")||e.message.startsWith("Client error ("),N0=async(e,t,n,r={},o=3,i=1e4)=>{let a;for(let s=0;s<=o;s+=1){let c=new AbortController,l=globalThis.setTimeout(()=>c.abort(),i);try{let u=await e(t,{method:"POST",headers:{"content-type":"application/json",...r},body:JSON.stringify(n),signal:c.signal});if(u.ok)return;let d=await u.text();if(u.status===401||u.status===403)throw Error("Authentication failed. Check your public key.");if(u.status>=400&&u.status<500&&u.status!==429)throw Error(`Client error (${u.status}): ${d}`);a=Error(u.status===429?`Rate limited (429): ${d}`:`Server error (${u.status}): ${d}`)}catch(u){let d=u instanceof Error?u.message:String(u);if(d.startsWith("Authentication failed")||d.startsWith("Client error ("))throw u instanceof Error?u:Error(d);a=u instanceof Error&&u.name==="AbortError"?Error("Request timed out"):u instanceof Error?u:Error(String(u))}finally{globalThis.clearTimeout(l)}if(s<o)await nx(JO*2**s)}throw Error(`Failed after ${o+1} attempts: ${a?.message??"Unknown error"}`)},U0=(e)=>e.resourceLogs?.reduce((t,n)=>t+(n.scopeLogs?.reduce((r,o)=>r+(o.logRecords?.length??0),0)??0),0)??0,nx=async(e,t)=>{if(t?.aborted)return;await new Promise((n)=>{let r=globalThis.setTimeout(n,e);t?.addEventListener("abort",()=>{globalThis.clearTimeout(r),n()},{once:!0})})},ox=(e,t,n)=>new Ye("BAD_REQUEST",{message:t,data:{operationId:e,missingContext:n}});var Ob=L(()=>{vr();VO();lt();g0=k.object({projectId:k.string().uuid().optional().describe("Project to tail logs for. Auto-filled from CLI and SDK context when omitted."),filters:wb.optional().describe("Optional filters applied by the tail SSE service.")}),h0=k.object({publicKey:k.string().min(1).describe("Public key for intake auth. Create or list one via the public key endpoints."),logs:k.custom((e)=>typeof e==="object"&&e!==null).describe("OTLP logs export request payload to send to the intake service.")}),f0=k.object({forwardedCount:k.number().int().nonnegative().describe("Number of log records accepted by the intake request."),failedCount:k.number().int().nonnegative().describe("Number of log records rejected by the intake request.")}),b0=new Set(["15006","3010"])});var ix;var rx=L(()=>{ix={me:{"~orpc":{errorMap:{},meta:{operationId:"me.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/me",tags:["Auth"],operationId:"me.get",summary:"Get the current credential",description:"Return the identity and available context for the current credential."}}},automations:{list:{"~orpc":{errorMap:{},meta:{operationId:"automations.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/automations",tags:["Automations"],operationId:"automations.list",summary:"List automations",description:"List scheduled automations in a project, with run health and recent run stats."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"automations.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/automations/{automationId}",tags:["Automations"],operationId:"automations.get",summary:"Get an automation",description:"Get a single automation by ID."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"automations.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/automations",tags:["Automations"],operationId:"automations.create",summary:"Create an automation",description:"Create an automation: either a cron-driven project script (see scripts.create) or a signal investigation bound to a signal definition (see signalDefinitions.create).",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"automations.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/automations/{automationId}",tags:["Automations"],operationId:"automations.update",summary:"Update an automation",description:"Update an automation's name, description, or schedule. Does not change which script it runs."}}},enable:{"~orpc":{errorMap:{},meta:{operationId:"automations.enable",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/automations/{automationId}/enable",tags:["Automations"],operationId:"automations.enable",summary:"Enable an automation",description:"Enable an automation so it runs on its schedule."}}},disable:{"~orpc":{errorMap:{},meta:{operationId:"automations.disable",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/automations/{automationId}/disable",tags:["Automations"],operationId:"automations.disable",summary:"Disable an automation",description:"Disable an automation so it stops running on its schedule."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"automations.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/automations/{automationId}",tags:["Automations"],operationId:"automations.delete",description:"Soft-delete a custom automation.",successStatus:204}}},runs:{list:{"~orpc":{errorMap:{},meta:{operationId:"automations.runs.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/automations/{automationId}/runs",tags:["Automations"],operationId:"automations.runs.list",summary:"List automation runs",description:"List runs for an automation, most recent first."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"automations.runs.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/automations/{automationId}/runs/{runId}",tags:["Automations"],operationId:"automations.runs.get",summary:"Get an automation run",description:"Get a single automation run by ID."}}},logs:{"~orpc":{errorMap:{},meta:{operationId:"automations.runs.logs",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/automations/{automationId}/runs/{runId}/logs",tags:["Automations"],operationId:"automations.runs.logs",summary:"Get automation run logs",description:"Get the captured stdout/stderr for a single automation run, reading the full output from durable storage when the inline preview was truncated."}}}}},artifacts:{list:{"~orpc":{errorMap:{},meta:{operationId:"artifacts.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/artifacts",tags:["Artifacts"],operationId:"artifacts.list",summary:"List artifacts",description:"List artifacts in a project with optional issue and date filters"}}},listIssueArtifacts:{"~orpc":{errorMap:{},meta:{operationId:"artifacts.listIssueArtifacts",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/issues/{issueId}/artifacts",tags:["Artifacts"],operationId:"artifacts.listIssueArtifacts",summary:"List artifacts for an issue",description:"List artifacts referenced by an issue report"}}},get:{"~orpc":{errorMap:{},meta:{operationId:"artifacts.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/artifacts/{artifactId}",tags:["Artifacts"],operationId:"artifacts.get",summary:"Get an artifact",description:"Get public metadata for an artifact"}}},download:{"~orpc":{errorMap:{},meta:{operationId:"artifacts.download",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/artifacts/{artifactId}/download",tags:["Artifacts"],operationId:"artifacts.download",summary:"Download an artifact",description:"Create a short-lived signed URL for an artifact"}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"artifacts.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/artifacts/{artifactId}",tags:["Artifacts"],operationId:"artifacts.delete",summary:"Delete an artifact",description:"Soft-delete an artifact from a project",successStatus:204}}}},automationTemplates:{list:{"~orpc":{errorMap:{},meta:{operationId:"automationTemplates.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/automation-templates",tags:["Automations"],operationId:"automationTemplates.list",summary:"List automation templates",description:"List the published Sazabi automation template catalog. Metadata only; template content (script bodies and prompts) is not exposed."}}}},dashboards:{list:{"~orpc":{errorMap:{},meta:{operationId:"dashboards.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/dashboards",tags:["Dashboards"],operationId:"dashboards.list",summary:"List dashboards",description:"List the project's dashboards by most recent update: title, description, revision, timestamps, and your capabilities. Metadata only; never runs queries."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"dashboards.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/dashboards/{id}",tags:["Dashboards"],operationId:"dashboards.get",summary:"Get a dashboard",description:"Read a dashboard's current MDX source (with its edit base), metadata, and static file descriptors. Set includeFiles to also receive the static file contents, giving a copy you can edit and pass back to dashboards.update. Never runs queries."}}},validate:{"~orpc":{errorMap:{},meta:{operationId:"dashboards.validate",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/dashboards/validate",tags:["Dashboards"],operationId:"dashboards.validate",summary:"Validate a dashboard",description:"Check dashboard MDX, static files, layout, query shapes, and your permission without saving or running queries. Optional: create and update always validate too. Each diagnostic carries its source line and column, component id, code, and repair hint."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"dashboards.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/dashboards",tags:["Dashboards"],operationId:"dashboards.create",summary:"Create a dashboard",description:"Save a new dashboard from one MDX document (DashboardMeta, layout, and inline Log Query Spec v2 artifacts) plus any static files it references by path. Generate the id yourself and reuse it on retries: an identical retry returns the original result. The response's editBase goes into DashboardMeta before the next update.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"dashboards.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/dashboards/{id}",tags:["Dashboards"],operationId:"dashboards.update",summary:"Update a dashboard",description:"Save the next revision from a complete edited MDX document. DashboardMeta.editBase must name the revision you edited (from dashboards.get or the last create/update); if the dashboard changed since, the update is rejected with 409 and the current revision so you can reconcile."}}},render:{"~orpc":{errorMap:{},meta:{operationId:"dashboards.render",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/dashboards/{id}/render",tags:["Dashboards"],operationId:"dashboards.render",summary:"Render a dashboard",description:"Run a saved dashboard's queries over one time window and return its layout with one outcome per requested component (ok, empty, rejected, or error). Omit timeRange for the dashboard's default window, revision for the current one, and componentIds for every bound component."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"dashboards.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/dashboards/{id}",tags:["Dashboards"],operationId:"dashboards.delete",summary:"Delete a dashboard",description:"Delete a dashboard if expectedRevision is still its current revision. Deleting an already-deleted dashboard succeeds again."}}}},logs:{ask:{"~orpc":{errorMap:{},meta:{operationId:"logs.ask",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/logs/ask",tags:["Logs"],operationId:"logs.ask",summary:"Ask about logs",description:"Answer a natural-language question about one project's stored logs. Returns a plain-language `answer`, what was measured over which window (`explanation`, `window`), how exact and complete the numbers are (`meta`), and a `queryId`. An overview (what is broken, recent errors, what changed, what is new, with no specific topic, field or request for lines) is searched: its results are the window's kinds of log lines, with their counts in the window and the window before and example lines; every other question is measured exactly. With `results: true` it also returns the rows, value, table, series or kinds of log lines the answer was written from. Pass the `queryId` to `logs.executeQuery` to run the same query again over any window with no model involved. When nothing matches, `status` is `not_found` and the answer says so, with how the question was read."}}},executeQuery:{"~orpc":{errorMap:{},meta:{operationId:"logs.executeQuery",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/logs/queries/{queryId}/execute",tags:["Logs"],operationId:"logs.executeQuery",summary:"Run an earlier log query",description:"Run the query behind an earlier `logs.ask` answer again, by its `queryId`, with no model involved: over the window the answer covered or a new one, with a new `limit`, or narrowed to the log lines of one `group` of a table. Returns `results` without an answer, and a new `queryId` whose `parentId` is the one that was run. An unknown id is not found; asking the question again yields a new id."}}}},logSources:{listProviders:{"~orpc":{errorMap:{},meta:{operationId:"logSources.listProviders",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/log-sources/providers",tags:["Log Sources"],operationId:"logSources.listProviders",summary:"List log source providers",description:"List all supported log source providers with their setup modes and metadata requirements."}}},list:{"~orpc":{errorMap:{},meta:{operationId:"logSources.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/log-sources",tags:["Log Sources"],operationId:"logSources.list",summary:"List log sources",description:"List log sources within one project."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"logSources.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/log-sources",tags:["Log Sources"],operationId:"logSources.create",summary:"Create a log source",description:"Create a log source. Managed mode takes vendor credentials in `metadata`, validates them, and provisions delivery behind the log source. Connectionless mode mints the log source plus a keyed log stream and returns the intake key and endpoint card(s) to point the sender at.",successStatus:201}}},get:{"~orpc":{errorMap:{},meta:{operationId:"logSources.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/log-sources/{logSourceId}",tags:["Log Sources"],operationId:"logSources.get",summary:"Get a log source",description:"Get one log source by ID, including its log streams and their endpoint card(s)."}}},verify:{"~orpc":{errorMap:{},meta:{operationId:"logSources.verify",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/log-sources/{logSourceId}/verify",tags:["Log Sources"],operationId:"logSources.verify",summary:"Check saved log source credentials",description:"Verify the saved managed credentials without provisioning or changing vendor resources. Unknown and transient outcomes preserve previous evidence."}}},update:{"~orpc":{errorMap:{},meta:{operationId:"logSources.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/log-sources/{logSourceId}",tags:["Log Sources"],operationId:"logSources.update",summary:"Update a log source",description:"Update a log source: pause or resume ingestion across its log streams, and/or set or clear its ongoing auto-provisioning filter. Log sources cannot be renamed — their generated names are immutable."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"logSources.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/log-sources/{logSourceId}",tags:["Log Sources"],operationId:"logSources.delete",summary:"Delete a log source",description:"Delete a log source. Tombstones the log source and its log streams, deactivates their intake keys (already-ingested data is preserved with its attribution), and runs vendor-side cleanup for managed log sources when the provider supports it.",successStatus:200}}}},logStreams:{list:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/log-streams",tags:["Log Streams"],operationId:"logStreams.list",summary:"List log streams",description:"List the log streams that belong to a log source."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/log-streams",tags:["Log Streams"],operationId:"logStreams.create",summary:"Create a log stream",description:"Create a new log stream under a managed log source. Triggers async provisioning; poll the log stream to track it. Connectionless log sources are single-stream — create another log source instead.",successStatus:201}}},createBatch:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.createBatch",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/log-streams/batch",tags:["Log Streams"],operationId:"logStreams.createBatch",summary:"Batch-create log streams",description:"Create multiple log streams under a managed log source in one call. Every accepted stream gets a durable row immediately; provisioning happens asynchronously — poll each log stream to track it. API-created streams are always nameless, so there is no per-item rejection: every request item is either accepted (a row was created) or the whole call fails with a request-level error.",successStatus:201}}},volumeStats:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.volumeStats",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/log-streams/volume-stats",tags:["Log Streams"],operationId:"logStreams.volumeStats",description:"Get bytes, log count, intake rate, and last-received time for each log stream in a log source over a bounded window."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/log-streams/{streamId}",tags:["Log Streams"],operationId:"logStreams.get",summary:"Get a log stream",description:"Get one log stream by ID. Use to poll provisioning status."}}},update:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/log-streams/{streamId}",tags:["Log Streams"],operationId:"logStreams.update",summary:"Update a log stream",description:"Update a log stream: pause or resume its ingestion. Log streams cannot be renamed."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/log-streams/{streamId}",tags:["Log Streams"],operationId:"logStreams.delete",summary:"Delete a log stream",description:"Delete a log stream. Tombstones the log stream and deactivates its intake key. Deleting a connectionless log source's only log stream tombstones the log source too.",successStatus:200}}},reassign:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.reassign",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/log-streams/{streamId}/reassign",tags:["Log Streams"],operationId:"logStreams.reassign",summary:"Reassign a log stream",description:"Move a log stream to a different connectionless log source in the same project. Preserves the stream's ID, intake key credential, and ingested data; rebinds the key's intake adapter to the target log source's provider so future data is processed as that provider's format.",successStatus:200}}}},connectedAccounts:{beginConnect:{"~orpc":{errorMap:{},meta:{operationId:"connectedAccounts.beginConnect",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/connected-accounts/connect",tags:["Connected Accounts"],operationId:"connectedAccounts.beginConnect",summary:"Begin a connected account connect flow",description:"Begin a browser connect flow for a connected-account provider. Returns a vendor URL to open in a browser and an attempt to poll; the vendor exchange completes server-side and no token ever reaches the caller.",successStatus:201}}},getConnectAttempt:{"~orpc":{errorMap:{},meta:{operationId:"connectedAccounts.getConnectAttempt",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/connected-accounts/connect/attempts/{attemptId}",tags:["Connected Accounts"],operationId:"connectedAccounts.getConnectAttempt",summary:"Get a connect attempt",description:"Poll a browser connect attempt started with `connectedAccounts.beginConnect`. Visible only to the user who began it."}}},list:{"~orpc":{errorMap:{},meta:{operationId:"connectedAccounts.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/connected-accounts",tags:["Connected Accounts"],operationId:"connectedAccounts.list",summary:"List connected accounts",description:"List the calling user's connected accounts for the organization."}}},disconnect:{"~orpc":{errorMap:{},meta:{operationId:"connectedAccounts.disconnect",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/connected-accounts/{provider}",tags:["Connected Accounts"],operationId:"connectedAccounts.disconnect",summary:"Disconnect a connected account",description:"Disconnect the calling user's connected account for a provider (soft delete)."}}}},integrations:{listProviders:{"~orpc":{errorMap:{},meta:{operationId:"integrations.listProviders",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/providers",tags:["Integrations"],operationId:"integrations.listProviders",summary:"List integration providers",description:"List supported integration providers and how many connections the organization has for each."}}},listConnections:{"~orpc":{errorMap:{},meta:{operationId:"integrations.listConnections",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connections",tags:["Integrations"],operationId:"integrations.listConnections",summary:"List integration connections",description:"List integration connections and their connection state for the organization."}}},getConnection:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getConnection",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connections/{connectionId}",tags:["Integrations"],operationId:"integrations.getConnection",summary:"Get an integration connection",description:"Get one integration connection by ID (non-secret config only)."}}},getLinearAutomationConfiguration:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getLinearAutomationConfiguration",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connections/{connectionId}/linear-automation",tags:["Integrations"],operationId:"integrations.getLinearAutomationConfiguration",summary:"Get Linear issue automation configuration",description:"Read the Linear team, project, and severity rules used to automatically create tickets for detected issues."}}},createConnection:{"~orpc":{errorMap:{},meta:{operationId:"integrations.createConnection",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/integrations/connections",tags:["Integrations"],operationId:"integrations.createConnection",summary:"Create an integration connection",description:"Create an integration connection for an api_key provider. Credentials are validated against the vendor, then stored encrypted.",successStatus:201}}},beginConnect:{"~orpc":{errorMap:{},meta:{operationId:"integrations.beginConnect",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/integrations/connect",tags:["Integrations"],operationId:"integrations.beginConnect",summary:"Begin a browser connect flow",description:"Begin a browser connect flow for an OAuth or app-installation provider. Returns a vendor URL to open in a browser and an attempt to poll; the vendor exchange completes server-side and no token ever reaches the caller.",successStatus:201}}},getConnectAttempt:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getConnectAttempt",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connect/attempts/{attemptId}",tags:["Integrations"],operationId:"integrations.getConnectAttempt",summary:"Get a connect attempt",description:"Poll a browser connect attempt started with `integrations.beginConnect`. Visible only to the user who began it."}}},getActiveCLIAttempt:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getActiveCLIAttempt",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connect/cli-attempt",tags:["Integrations"],operationId:"integrations.getActiveCLIAttempt",summary:"Get an active CLI connect attempt",description:"Return the newest pending, non-expired CLI-initiated connect attempt for the given provider, or null if none exists. Used by the dashboard to show a 'connection in progress from your terminal' message."}}},disconnectConnection:{"~orpc":{errorMap:{},meta:{operationId:"integrations.disconnectConnection",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/integrations/connections/{connectionId}",tags:["Integrations"],operationId:"integrations.disconnectConnection",summary:"Disconnect an integration connection",description:"Disconnect an integration connection (soft delete). Always succeeds regardless of stored credential state; cached vendor catalogs and routing derived from the connection are removed."}}},updateConnectionCredentials:{"~orpc":{errorMap:{},meta:{operationId:"integrations.updateConnectionCredentials",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/integrations/connections/{connectionId}/credentials",tags:["Integrations"],operationId:"integrations.updateConnectionCredentials",summary:"Update integration connection credentials",description:"Replace an api_key connection's credentials in place — the reconnect path for a connection that needs attention. Keeps connection-scoped configuration."}}},updateLinearAutomationConfiguration:{"~orpc":{errorMap:{},meta:{operationId:"integrations.updateLinearAutomationConfiguration",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/integrations/connections/{connectionId}/linear-automation",tags:["Integrations"],operationId:"integrations.updateLinearAutomationConfiguration",summary:"Update Linear issue automation configuration",description:"Set the Linear team, optional project, and per-severity ticket creation rules for detected issues."}}},getOrganizationExternalIdentityJitPolicy:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getOrganizationExternalIdentityJitPolicy",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/external-identity-jit-policy",tags:["Integrations"],operationId:"integrations.getOrganizationExternalIdentityJitPolicy",summary:"Get the organization external-identity JIT policy",description:"Read the organization's stored external-identity JIT policy."}}},updateOrganizationExternalIdentityJitPolicy:{"~orpc":{errorMap:{},meta:{operationId:"integrations.updateOrganizationExternalIdentityJitPolicy",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/integrations/external-identity-jit-policy",tags:["Integrations"],operationId:"integrations.updateOrganizationExternalIdentityJitPolicy",summary:"Update the organization external-identity JIT policy",description:"Enable or disable external-identity JIT across an organization."}}},getConnectionExternalIdentityJitPolicy:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getConnectionExternalIdentityJitPolicy",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connections/{connectionId}/external-identity-jit-policy",tags:["Integrations"],operationId:"integrations.getConnectionExternalIdentityJitPolicy",summary:"Get a connection external-identity JIT policy",description:"Read stored and effective JIT policy for one connection."}}},updateConnectionExternalIdentityJitPolicy:{"~orpc":{errorMap:{},meta:{operationId:"integrations.updateConnectionExternalIdentityJitPolicy",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/integrations/connections/{connectionId}/external-identity-jit-policy",tags:["Integrations"],operationId:"integrations.updateConnectionExternalIdentityJitPolicy",summary:"Update a connection external-identity JIT policy",description:"Enable or disable external-identity JIT for one connection."}}},getMicrosoftTeamsAdminConsent:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getMicrosoftTeamsAdminConsent",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connections/{connectionId}/microsoft-teams-admin-consent",tags:["Integrations"],operationId:"integrations.getMicrosoftTeamsAdminConsent",summary:"Get the Microsoft Teams tenant admin-consent status",description:"Read the recorded Microsoft tenant admin-consent status for a Teams connection, with a consent URL for retrying the grant."}}},getSlackConfiguration:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getSlackConfiguration",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connections/{connectionId}/slack-configuration",tags:["Integrations"],operationId:"integrations.getSlackConfiguration",summary:"Get Slack connection configuration",description:"Read Slack connection configuration (default project, automatic responses, acknowledgement message)."}}},updateSlackConfiguration:{"~orpc":{errorMap:{},meta:{operationId:"integrations.updateSlackConfiguration",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/integrations/connections/{connectionId}/slack-configuration",tags:["Integrations"],operationId:"integrations.updateSlackConfiguration",summary:"Update Slack connection configuration",description:"Update Slack connection configuration. Omitted fields are left unchanged."}}},createSlackChannel:{"~orpc":{errorMap:{},meta:{operationId:"integrations.createSlackChannel",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/integrations/slack/channels",tags:["Integrations"],operationId:"integrations.createSlackChannel",summary:"Create a Slack channel",description:"Create a public channel in the organization's connected Slack workspace and invite the calling user. Requires the Slack connection to hold the channels:manage bot scope. The new channel appears as an alert destination once the channel catalog refresh completes.",successStatus:201}}},listSlackChannelProjectMappings:{"~orpc":{errorMap:{},meta:{operationId:"integrations.listSlackChannelProjectMappings",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connections/{connectionId}/slack-channel-project-mappings",tags:["Integrations"],operationId:"integrations.listSlackChannelProjectMappings",summary:"List Slack channel-to-project mappings",description:"List channel-to-project mappings for a Slack connection."}}},setSlackChannelProjectMapping:{"~orpc":{errorMap:{},meta:{operationId:"integrations.setSlackChannelProjectMapping",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PUT",path:"/integrations/connections/{connectionId}/slack-channel-project-mappings/{slackChannelId}",tags:["Integrations"],operationId:"integrations.setSlackChannelProjectMapping",summary:"Set a Slack channel-to-project mapping",description:"Create or update the channel-to-project mapping for one Slack channel. Idempotent on (connection, channel)."}}},deleteSlackChannelProjectMapping:{"~orpc":{errorMap:{},meta:{operationId:"integrations.deleteSlackChannelProjectMapping",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/integrations/connections/{connectionId}/slack-channel-project-mappings/{slackChannelId}",tags:["Integrations"],operationId:"integrations.deleteSlackChannelProjectMapping",summary:"Delete a Slack channel-to-project mapping",description:"Delete a channel-to-project mapping."}}}},notificationChannels:{getProject:{"~orpc":{errorMap:{},meta:{operationId:"notificationChannels.getProject",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/notification-channels",tags:["Notification channels"],operationId:"notificationChannels.getProject",summary:"List project notification channels",description:"List a project's notification channels with preferences, prerequisites, connection state, configured destinations, and supported notification types."}}}},notificationDeliveryRules:{list:{"~orpc":{errorMap:{},meta:{operationId:"notificationDeliveryRules.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/notification-delivery-rules",tags:["Notification delivery rules"],operationId:"notificationDeliveryRules.list",summary:"List delivery rules",description:"List the positive delivery rules for a project."}}},options:{"~orpc":{errorMap:{},meta:{operationId:"notificationDeliveryRules.options",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/notification-delivery-rules/options",tags:["Notification delivery rules"],operationId:"notificationDeliveryRules.options",summary:"Get delivery rule options",description:"List available destinations, events, and conditions for project delivery rules."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"notificationDeliveryRules.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/notification-delivery-rules",tags:["Notification delivery rules"],operationId:"notificationDeliveryRules.create",summary:"Create a delivery rule",description:"Create a positive project notification delivery rule."}}},update:{"~orpc":{errorMap:{},meta:{operationId:"notificationDeliveryRules.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PUT",path:"/notification-delivery-rules/{ruleId}",tags:["Notification delivery rules"],operationId:"notificationDeliveryRules.update",summary:"Update a delivery rule",description:"Replace a positive delivery rule atomically."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"notificationDeliveryRules.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/notification-delivery-rules/{ruleId}",tags:["Notification delivery rules"],operationId:"notificationDeliveryRules.delete",summary:"Delete a delivery rule",description:"Delete a positive delivery rule without deleting its reusable destinations."}}}},taskCreationRules:{list:{"~orpc":{errorMap:{},meta:{operationId:"taskCreationRules.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/task-creation-rules",tags:["Task creation rules"],operationId:"taskCreationRules.list",summary:"List task creation rules",description:"List the automatic task creation rules for a project in evaluation priority order."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"taskCreationRules.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/task-creation-rules/{ruleId}",tags:["Task creation rules"],operationId:"taskCreationRules.get",summary:"Get a task creation rule",description:"Get a single task creation rule by ID."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"taskCreationRules.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/task-creation-rules",tags:["Task creation rules"],operationId:"taskCreationRules.create",summary:"Create a task creation rule",description:"Create an automatic task creation rule that files tickets in a connected tracker when issues trigger.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"taskCreationRules.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/task-creation-rules/{ruleId}",tags:["Task creation rules"],operationId:"taskCreationRules.update",summary:"Update a task creation rule",description:"Update an automatic task creation rule."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"taskCreationRules.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/task-creation-rules/{ruleId}",tags:["Task creation rules"],operationId:"taskCreationRules.delete",summary:"Delete a task creation rule",description:"Soft-delete an automatic task creation rule."}}},reorder:{"~orpc":{errorMap:{},meta:{operationId:"taskCreationRules.reorder",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/task-creation-rules/reorder",tags:["Task creation rules"],operationId:"taskCreationRules.reorder",summary:"Reorder task creation rules",description:"Atomically reorder all task creation rules for a project, assigning priorities matching the array order."}}}},mcpConnectors:{listProviders:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.listProviders",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/mcp-connectors/providers",tags:["MCP Connectors"],operationId:"mcpConnectors.listProviders",summary:"List MCP connector providers",description:"List all supported MCP connector providers with their auth mode and setup skill."}}},list:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/mcp-connectors",tags:["MCP Connectors"],operationId:"mcpConnectors.list",summary:"List MCP connectors",description:"List configured MCP connectors within one project with provider, status, and enabled-tool count."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/mcp-connectors/{connectionId}",tags:["MCP Connectors"],operationId:"mcpConnectors.get",summary:"Get an MCP connector",description:"Get one configured MCP connector by connection ID."}}},details:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.details",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/mcp-connectors/{connectionId}/details",tags:["MCP Connectors"],operationId:"mcpConnectors.details",summary:"Inspect an MCP connector's tools",description:"Inspect one MCP connector's tool surface, including each tool's name, description, and read-only status."}}},search:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.search",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/mcp-connectors/tools/search",tags:["MCP Connectors"],operationId:"mcpConnectors.search",summary:"Search MCP connector tools",description:"Search executable third-party MCP connector tools by free-text query. Empty query lists connectors; empty query plus namespace enumerates that connector. Hits omit input schemas unless includeInputSchema is true, which requires one exact namespaced tool and always returns at most one hit."}}},describe:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.describe",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/mcp-connectors/tools/describe",tags:["MCP Connectors"],operationId:"mcpConnectors.describe",summary:"Describe an MCP connector tool",description:"Load one executable third-party MCP connector tool, including its input schema."}}},call:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.call",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/mcp-connectors/tools/call",tags:["MCP Connectors"],operationId:"mcpConnectors.call",summary:"Call an MCP connector tool",description:"Invoke one executable third-party MCP connector tool using that connection's stored credential."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/mcp-connectors",tags:["MCP Connectors"],operationId:"mcpConnectors.create",summary:"Create an MCP connector",description:"Create a preset MCP connector with header-based or AWS SigV4 authentication. The server URL must match the selected provider's supported endpoints. Connects immediately and returns the connector with its discovered tool snapshot.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/mcp-connectors/{connectionId}",tags:["MCP Connectors"],operationId:"mcpConnectors.update",summary:"Update an MCP connector",description:"Replace credentials on an existing preset MCP connector and retry discovery while preserving its identity and tool policy. Supply providerId to reject a connector from a different provider before any credentials are used. Omit credentials to retry discovery with saved credentials. OAuth connectors use the OAuth reconnect operation."}}},disconnect:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.disconnect",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/mcp-connectors/{connectionId}",tags:["MCP Connectors"],operationId:"mcpConnectors.disconnect",summary:"Disconnect an MCP connector",description:"Disconnect and permanently remove an MCP connector.",successStatus:204}}},setReadOnly:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.setReadOnly",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/mcp-connectors/{connectionId}/read-only",tags:["MCP Connectors"],operationId:"mcpConnectors.setReadOnly",summary:"Toggle an MCP connector's read-only mode",description:"Toggle the read-only restriction on an MCP connector."}}},beginOAuthInstall:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.beginOAuthInstall",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/mcp-connectors/oauth/begin",tags:["MCP Connectors"],operationId:"mcpConnectors.beginOAuthInstall",summary:"Begin an MCP connector OAuth install",description:"Begin an OAuth browser flow to install or reconnect a preset MCP connector. Open the authorization URL in the user's browser, then poll getMcpOAuthInstallAttempt with the returned connectionId and requestId to check this attempt's completion.",successStatus:201}}},getOAuthInstallAttempt:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.getOAuthInstallAttempt",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/mcp-connectors/oauth/attempts/{connectionId}",tags:["MCP Connectors"],operationId:"mcpConnectors.getOAuthInstallAttempt",summary:"Get an MCP connector OAuth install attempt",description:"Poll the status of an in-progress OAuth MCP connector install. Returns authorizing while the user completes the browser flow, connected on success, or error on failure."}}}},sandboxEnvironmentVariables:{list:{"~orpc":{errorMap:{},meta:{operationId:"sandboxEnvironmentVariables.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/sandbox-environment-variables",tags:["Sandbox Environment Variables"],operationId:"sandboxEnvironmentVariables.list",summary:"List sandbox environment variables",description:"List configured custom sandbox environment variable keys for a project without exposing secret values."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"sandboxEnvironmentVariables.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/sandbox-environment-variables/{key}",tags:["Sandbox Environment Variables"],operationId:"sandboxEnvironmentVariables.get",summary:"Get sandbox environment variable",description:"Check whether a specific custom sandbox environment variable is configured for a project."}}},upsert:{"~orpc":{errorMap:{},meta:{operationId:"sandboxEnvironmentVariables.upsert",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/sandbox-environment-variables",tags:["Sandbox Environment Variables"],operationId:"sandboxEnvironmentVariables.upsert",summary:"Upsert sandbox environment variables",description:"Set or update custom sandbox environment variables for a project. Merges provided variables with existing ones. Values are encrypted server-side and never returned.",successStatus:200}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"sandboxEnvironmentVariables.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/sandbox-environment-variables/{key}",tags:["Sandbox Environment Variables"],operationId:"sandboxEnvironmentVariables.delete",summary:"Delete sandbox environment variable",description:"Delete a custom sandbox environment variable from a project by key name."}}}},sandboxInitScript:{get:{"~orpc":{errorMap:{},meta:{operationId:"sandboxInitScript.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/sandbox/init-script",tags:["Sandbox Init Script"],operationId:"sandboxInitScript.get",summary:"Get sandbox init script",description:"Fetch the custom sandbox initialization script configured for a project."}}},upsert:{"~orpc":{errorMap:{},meta:{operationId:"sandboxInitScript.upsert",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PUT",path:"/sandbox/init-script",tags:["Sandbox Init Script"],operationId:"sandboxInitScript.upsert",summary:"Upsert sandbox init script",description:"Set or replace the custom sandbox initialization script for a project.",successStatus:200}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"sandboxInitScript.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/sandbox/init-script",tags:["Sandbox Init Script"],operationId:"sandboxInitScript.delete",summary:"Delete sandbox init script",description:"Delete the custom sandbox initialization script from a project."}}}},sandboxClis:{deleteCli:{"~orpc":{errorMap:{},meta:{operationId:"sandboxClis.deleteCli",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/sandbox-clis/config/{cliType}",tags:["Sandbox CLIs"],operationId:"sandboxClis.deleteCli",summary:"Disconnect CLI",description:"Delete a project's stored CLI connection. Integration-managed access remains available until its owning integration is disconnected."}}},listConnections:{"~orpc":{errorMap:{},meta:{operationId:"sandboxClis.listConnections",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/sandbox-clis/connections",tags:["Sandbox CLIs"],operationId:"sandboxClis.listConnections",summary:"List CLI connections",description:"List a project's stored and integration-backed sandbox CLI connections without returning secret values."}}},listTypes:{"~orpc":{errorMap:{},meta:{operationId:"sandboxClis.listTypes",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/sandbox-clis/types",tags:["Sandbox CLIs"],operationId:"sandboxClis.listTypes",summary:"List CLI types",description:"List all supported sandbox CLI types with their environment variable requirements and setup skills."}}},testCli:{"~orpc":{errorMap:{},meta:{operationId:"sandboxClis.testCli",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/sandbox-clis/test",tags:["Sandbox CLIs"],operationId:"sandboxClis.testCli",summary:"Test CLI connection",description:"Validate unsaved CLI credentials in a read-only ephemeral sandbox without persisting them."}}},verify:{"~orpc":{errorMap:{},meta:{operationId:"sandboxClis.verify",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/sandbox-clis/{cliType}/verify",tags:["Sandbox CLIs"],operationId:"sandboxClis.verify",summary:"Check saved CLI credentials",description:"Check the current saved credentials and record authoritative results. Transient failures leave prior evidence unchanged."}}},upsertCli:{"~orpc":{errorMap:{},meta:{operationId:"sandboxClis.upsertCli",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/sandbox-clis/config",tags:["Sandbox CLIs"],operationId:"sandboxClis.upsertCli",summary:"Upsert CLI connection",description:"Set or replace a project's CLI connection credentials (e.g. the kubectl CLI's KUBECONFIG_CONTENTS). Values are encrypted server-side and never returned. Requires write access to the target project.",successStatus:200}}}},scripts:{list:{"~orpc":{errorMap:{},meta:{operationId:"scripts.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/scripts",tags:["Scripts"],operationId:"scripts.list",summary:"List scripts",description:"List durable bash scripts stored for a project."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"scripts.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/scripts/{name}",tags:["Scripts"],operationId:"scripts.get",summary:"Get a script",description:"Get a single project script by name, including its body."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"scripts.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/scripts",tags:["Scripts"],operationId:"scripts.create",summary:"Create a script",description:"Create a durable bash script for a project.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"scripts.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/scripts/{name}",tags:["Scripts"],operationId:"scripts.update",summary:"Update a script",description:"Update a project script's body and/or description."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"scripts.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/scripts/{name}",tags:["Scripts"],operationId:"scripts.delete",summary:"Delete a script",description:"Soft-delete a project script by name.",successStatus:204}}}},signalDefinitions:{list:{"~orpc":{errorMap:{},meta:{operationId:"signalDefinitions.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/signal-definitions",tags:["Signal definitions"],operationId:"signalDefinitions.list",summary:"List signal definitions",description:"List signal definitions in a project."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"signalDefinitions.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/signal-definitions/{signalDefinitionId}",tags:["Signal definitions"],operationId:"signalDefinitions.get",summary:"Get a signal definition",description:"Get a single signal definition by ID."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"signalDefinitions.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/signal-definitions",tags:["Signal definitions"],operationId:"signalDefinitions.create",summary:"Create a signal definition",description:"Create a CEL signal definition for a project.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"signalDefinitions.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/signal-definitions/{signalDefinitionId}",tags:["Signal definitions"],operationId:"signalDefinitions.update",summary:"Update a signal definition",description:"Update a signal definition's name, CEL body, or enabled state."}}},disable:{"~orpc":{errorMap:{},meta:{operationId:"signalDefinitions.disable",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/signal-definitions/{signalDefinitionId}/disable",tags:["Signal definitions"],operationId:"signalDefinitions.disable",summary:"Disable a signal definition",description:"Disable a signal definition so it stops matching logs."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"signalDefinitions.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/signal-definitions/{signalDefinitionId}",tags:["Signal definitions"],operationId:"signalDefinitions.delete",summary:"Delete a signal definition",description:"Permanently delete a signal definition.",successStatus:204}}}},memory:{put:{"~orpc":{errorMap:{},meta:{operationId:"memory.put",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PUT",path:"/memory",tags:["Memory"],operationId:"memory.put",summary:"Create or replace a memory document",description:"Create or replace a curated project memory document. Embeds on success."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"memory.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/memory",tags:["Memory"],operationId:"memory.create",summary:"Create a memory document",description:"Create a curated project memory document at a path that holds no document. Fails with a conflict when the path already exists; never replaces a document. Embeds on success.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"memory.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/memory/document",tags:["Memory"],operationId:"memory.update",summary:"Update a memory document",description:"Replace the body of an existing curated project memory document. Fails with not found when no document exists at the path; never creates one. Embeds on success."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"memory.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/memory/document",tags:["Memory"],operationId:"memory.get",summary:"Get a memory document",description:"Get one project memory document by id or path."}}},list:{"~orpc":{errorMap:{},meta:{operationId:"memory.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/memory",tags:["Memory"],operationId:"memory.list",summary:"List memory documents",description:"List project memory catalog rows without embedding search."}}},search:{"~orpc":{errorMap:{},meta:{operationId:"memory.search",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/memory/search",tags:["Memory"],operationId:"memory.search",summary:"Search project memory",description:"Hybrid semantic and keyword search over project memory documents."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"memory.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/memory/document",tags:["Memory"],operationId:"memory.delete",summary:"Delete a memory document",description:"Soft-delete a curated project memory document by id or path.",successStatus:204}}}},supportTickets:{create:{"~orpc":{errorMap:{},meta:{operationId:"supportTickets.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/support-tickets",tags:["Support Tickets"],operationId:"supportTickets.create",summary:"File a support ticket",description:"File a support ticket or feature request with Sazabi support. The requester is the authenticated person; replies arrive in the dashboard support widget and by email.",successStatus:201}}},availability:{"~orpc":{errorMap:{},meta:{operationId:"supportTickets.availability",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/support-tickets/availability",tags:["Support Tickets"],operationId:"supportTickets.availability",summary:"Check whether support tickets can be filed",description:"Report whether this environment can file support tickets: the support desk is configured and reachable."}}}},onboarding:{continueWithFree:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.continueWithFree",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/onboarding/continue-with-free",tags:["Onboarding"],operationId:"onboarding.continueWithFree",summary:"Continue onboarding with Free",description:"Confirm the organization's existing active Free plan. Requires billing management permission; does not create a subscription or request payment."}}},ensureDefaultProject:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.ensureDefaultProject",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/onboarding/ensure-default-project",tags:["Onboarding"],operationId:"onboarding.ensureDefaultProject",summary:"Ensure the default project",description:"Create the organization's default project unless it already has an active one, and return whichever applies. Atomic per organization, so concurrent onboarding surfaces cannot create duplicates. Requires settings write permission."}}},getState:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.getState",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/onboarding/state",tags:["Onboarding"],operationId:"onboarding.getState",summary:"Get onboarding state",description:"Read onboarding progress for the authenticated user."}}},skipIntegration:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.skipIntegration",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/onboarding/skip-integration",tags:["Onboarding"],operationId:"onboarding.skipIntegration",summary:"Skip an integration step",description:"Skip a GitHub or Slack integration step during onboarding."}}},skipGithubAppInstallation:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.skipGithubAppInstallation",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/onboarding/skip-github-app",tags:["Onboarding"],operationId:"onboarding.skipGithubAppInstallation",summary:"Skip GitHub App installation",description:"Skip GitHub App installation during onboarding."}}},skipSampleIssue:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.skipSampleIssue",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/onboarding/skip-sample-issue",tags:["Onboarding"],operationId:"onboarding.skipSampleIssue",summary:"Skip the test issue",description:"Skip the optional test issue during onboarding."}}},completeSampleIssue:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.completeSampleIssue",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/onboarding/complete-sample-issue",tags:["Onboarding"],operationId:"onboarding.completeSampleIssue",summary:"Complete the test issue step",description:"Mark the sample-issue onboarding step complete after viewing the test issue."}}},finish:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.finish",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/onboarding/finish",tags:["Onboarding"],operationId:"onboarding.finish",summary:"Finish onboarding",description:"Mark onboarding complete when all prerequisites are satisfied."}}}},organizations:{list:{"~orpc":{errorMap:{},meta:{operationId:"organizations.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/organizations",tags:["Organizations"],operationId:"organizations.list",summary:"List organizations",description:"List organizations available to the current credential."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"organizations.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/organizations/{organizationId}",tags:["Organizations"],operationId:"organizations.get",summary:"Get an organization",description:"Get one organization by ID."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"organizations.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/organizations",tags:["Organizations"],operationId:"organizations.create",summary:"Create an organization",description:"Create an organization for the authenticated user.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"organizations.update",backend:"api",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}}}]},route:{method:"PATCH",path:"/organizations/{organizationId}",tags:["Organizations"],operationId:"organizations.update",summary:"Update an organization",description:"Update one organization."}}}},members:{list:{"~orpc":{errorMap:{},meta:{operationId:"members.list",backend:"api",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"}]}}]},route:{method:"GET",path:"/members",tags:["Members"],operationId:"members.list",summary:"List members",description:"List members in an organization."}}},updateRole:{"~orpc":{errorMap:{},meta:{operationId:"members.updateRole",backend:"api",pagination:"none",async:"sync",examples:[{name:"promote-member",input:{organizationId:"organization-123",member:"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"}}}]},route:{method:"PATCH",path:"/members/{member}/role",tags:["Members"],operationId:"members.updateRole",summary:"Update a member's role",description:"Update a member's organization role."}}},remove:{"~orpc":{errorMap:{},meta:{operationId:"members.remove",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/members/{member}",tags:["Members"],operationId:"members.remove",summary:"Remove a member",description:"Remove a member from an organization.",inputStructure:"detailed"}}},invite:{"~orpc":{errorMap:{},meta:{operationId:"members.invite",backend:"api",pagination:"none",async:"sync",examples:[{name:"invite-member",input:{organizationId:"organization-123",email:"newhire@example.com",role:"member"},output:{invitation:{id:"invitation-123",email:"newhire@example.com",role:"member",status:"pending",createdAt:"2026-01-01T00:00:00.000Z",expiresAt:"2026-01-08T00:00:00.000Z"}}}]},route:{method:"POST",path:"/members/invitations",tags:["Members"],operationId:"members.invite",summary:"Invite a member",description:"Invite a person to the organization by email.",successStatus:201}}},listInvitations:{"~orpc":{errorMap:{},meta:{operationId:"members.listInvitations",backend:"api",pagination:"none",async:"sync",examples:[{name:"organization-invitations",input:{organizationId:"organization-123"},output:{invitations:[{id:"invitation-123",email:"newhire@example.com",role:"member",status:"pending",createdAt:"2026-01-01T00:00:00.000Z",expiresAt:"2026-01-08T00:00:00.000Z"}]}}]},route:{method:"GET",path:"/members/invitations",tags:["Members"],operationId:"members.listInvitations",summary:"List invitations",description:"List pending invitations for an organization."}}},revokeInvitation:{"~orpc":{errorMap:{},meta:{operationId:"members.revokeInvitation",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/members/invitations/{invitationId}",tags:["Members"],operationId:"members.revokeInvitation",summary:"Revoke an invitation",description:"Revoke a pending invitation.",inputStructure:"detailed"}}}},teams:{list:{"~orpc":{errorMap:{},meta:{operationId:"teams.list",backend:"api",pagination:"none",async:"sync",examples:[{name:"organization-teams",input:{organizationId:"organization-123"},output:{teams:[{id:"5c0f9866-31ab-4237-94cc-a1d0ba2f6de2",name:"Payments",description:"Owns checkout and billing components.",createdAt:"2026-01-01T00:00:00.000Z",memberCount:4}]}}]},route:{method:"GET",path:"/teams",tags:["Teams"],operationId:"teams.list",summary:"List teams",description:"List teams in an organization."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"teams.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/teams",tags:["Teams"],operationId:"teams.create",summary:"Create a team",description:"Create a team in an organization.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"teams.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/teams/{teamId}",tags:["Teams"],operationId:"teams.update",summary:"Update a team",description:"Rename a team or update its description."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"teams.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/teams/{teamId}",tags:["Teams"],operationId:"teams.delete",summary:"Delete a team",description:"Delete a team, its memberships, and its component-ownership assignments.",inputStructure:"detailed"}}},addMember:{"~orpc":{errorMap:{},meta:{operationId:"teams.addMember",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/teams/{teamId}/members",tags:["Teams"],operationId:"teams.addMember",summary:"Add a team member",description:"Add an active organization member to a team.",successStatus:201}}},removeMember:{"~orpc":{errorMap:{},meta:{operationId:"teams.removeMember",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/teams/{teamId}/members/{userId}",tags:["Teams"],operationId:"teams.removeMember",summary:"Remove a team member",description:"Remove a member from a team.",inputStructure:"detailed"}}},listMembers:{"~orpc":{errorMap:{},meta:{operationId:"teams.listMembers",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/teams/{teamId}/members",tags:["Teams"],operationId:"teams.listMembers",summary:"List team members",description:"List a team's active members."}}}},publicKeys:{list:{"~orpc":{errorMap:{},meta:{operationId:"publicKeys.list",backend:"api",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,deactivatedAt:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}],nextCursor:null}}]},route:{method:"GET",path:"/public-keys",tags:["Public Keys"],operationId:"publicKeys.list",summary:"List public keys",description:"List public keys within one project."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"publicKeys.get",backend:"api",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,deactivatedAt:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}}}]},route:{method:"GET",path:"/public-keys/{keyId}",tags:["Public Keys"],operationId:"publicKeys.get",summary:"Get a public key",description:"Get one public key within one project."}}},ensureLogForwarding:{"~orpc":{errorMap:{},meta:{operationId:"publicKeys.ensureLogForwarding",backend:"api",pagination:"none",async:"sync",examples:[{name:"ensure-log-forwarding-public-key",input:{projectId:"11111111-1111-4111-8111-111111111111"},output:{publicKey:{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",name:"sazabi-cli-forward",dataSourceConnectionId:null,deactivatedAt:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z",value:"sazabi_public_example"}}}]},route:{method:"POST",path:"/public-keys/log-forwarding/ensure",tags:["Public Keys"],operationId:"publicKeys.ensureLogForwarding",summary:"Ensure a log forwarding public key",description:"Ensure a reusable project-scoped public key exists for CLI log forwarding."}}},update:{"~orpc":{errorMap:{},meta:{operationId:"publicKeys.update",backend:"api",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,deactivatedAt:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}}}]},route:{method:"PATCH",path:"/public-keys/{keyId}",tags:["Public Keys"],operationId:"publicKeys.update",summary:"Update a public key",description:"Update one public key within one project."}}},deactivate:{"~orpc":{errorMap:{},meta:{operationId:"publicKeys.deactivate",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/public-keys/{keyId}/deactivate",tags:["Public Keys"],operationId:"publicKeys.deactivate",summary:"Deactivate a public key",description:"Deactivate one public key within one project. Recently validated requests may continue to authenticate for a short period after deactivation.",inputStructure:"detailed"}}}},secretKeys:{list:{"~orpc":{errorMap:{},meta:{operationId:"secretKeys.list",backend:"api",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}}]},route:{method:"GET",path:"/secret-keys",tags:["Secret Keys"],operationId:"secretKeys.list",summary:"List secret keys",description:"List secret keys within the organization."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"secretKeys.get",backend:"api",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"}}}]},route:{method:"GET",path:"/secret-keys/{keyId}",tags:["Secret Keys"],operationId:"secretKeys.get",summary:"Get a secret key",description:"Get one secret key within the organization."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"secretKeys.create",backend:"api",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"}}}]},route:{method:"POST",path:"/secret-keys",tags:["Secret Keys"],operationId:"secretKeys.create",summary:"Create a secret key",description:"Create one secret key within the organization.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"secretKeys.update",backend:"api",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"}}}]},route:{method:"PATCH",path:"/secret-keys/{keyId}",tags:["Secret Keys"],operationId:"secretKeys.update",summary:"Update a secret key",description:"Update one secret key within the organization."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"secretKeys.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/secret-keys/{keyId}",tags:["Secret Keys"],operationId:"secretKeys.delete",summary:"Delete a secret key",description:"Delete one secret key within the organization.",successStatus:204,inputStructure:"detailed"}}}},projects:{list:{"~orpc":{errorMap:{},meta:{operationId:"projects.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/projects",tags:["Projects"],operationId:"projects.list",summary:"List projects",description:"List projects in an organization."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"projects.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/projects/{projectId}",tags:["Projects"],operationId:"projects.get",summary:"Get a project",description:"Get one project by ID."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"projects.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/projects",tags:["Projects"],operationId:"projects.create",summary:"Create a project",description:"Create one project in an organization.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"projects.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/projects/{projectId}",tags:["Projects"],operationId:"projects.update",summary:"Update a project",description:"Update (rename) one project by ID. User credentials require the `settings:write` organization permission (admin or owner role)."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"projects.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/projects/{projectId}",tags:["Projects"],operationId:"projects.delete",summary:"Delete a project",description:"Delete one project by ID. User credentials require the `settings:write` organization permission (admin or owner role).",successStatus:204}}}},search:{threads:{"~orpc":{errorMap:{},meta:{operationId:"search.threads",backend:"api",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}}}]},route:{method:"GET",path:"/search/threads",tags:["Search"],operationId:"search.threads",summary:"Search threads",description:"Search threads within one project."}}},messages:{"~orpc":{errorMap:{},meta:{operationId:"search.messages",backend:"api",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}}}]},route:{method:"GET",path:"/search/messages",tags:["Search"],operationId:"search.messages",summary:"Search messages",description:"Search messages within one project."}}}},messages:{list:{"~orpc":{errorMap:{},meta:{operationId:"messages.list",backend:"api",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?"}],source:"api",createdAt:"2026-01-01T00:00:00.000Z"}],nextCursor:null}}]},route:{method:"GET",path:"/threads/{threadId}/messages",tags:["Messages"],operationId:"messages.list",summary:"List messages in a thread",description:"List messages in a thread with cursor pagination."}}},append:{"~orpc":{errorMap:{},meta:{operationId:"messages.append",backend:"api",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,failureClass:null,failureRetryable:null}}]},route:{method:"POST",path:"/threads/{threadId}/messages",tags:["Messages"],operationId:"messages.append",summary:"Append a message to a thread",description:"Append a user message to an existing thread and trigger a deferred run.",successStatus:201}}}},threads:{list:{"~orpc":{errorMap:{},meta:{operationId:"threads.list",backend:"api",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",source:"api",createdAt:"2026-01-01T00:00:00.000Z",updatedAt:"2026-01-01T00:05:00.000Z"}],nextCursor:null}}]},route:{method:"GET",path:"/threads",tags:["Threads"],operationId:"threads.list",summary:"List threads",description:"List threads in a project, optionally filtered by status."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"threads.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/threads/{threadId}",tags:["Threads"],operationId:"threads.get",summary:"Get a thread",description:"Get a thread and its messages."}}},getStatus:{"~orpc":{errorMap:{},meta:{operationId:"threads.getStatus",backend:"api",pagination:"none",async:"sync",examples:[{name:"processing-thread",input:{threadId:"22222222-2222-4222-8222-222222222222"},output:{status:"processing",lastRunStatus:null}}]},route:{method:"GET",path:"/threads/{threadId}/status",tags:["Threads"],operationId:"threads.getStatus",summary:"Get a thread's status",description:"Get the current processing status for a thread."}}},stop:{"~orpc":{errorMap:{},meta:{operationId:"threads.stop",backend:"api",pagination:"none",async:"sync",examples:[{name:"stop-processing-thread",input:{threadId:"22222222-2222-4222-8222-222222222222"},output:{success:!0}}]},route:{method:"POST",path:"/threads/{threadId}/stop",tags:["Threads"],operationId:"threads.stop",summary:"Stop a thread's run",description:"Stop a thread's in-flight run. Idempotent and best-effort: returns success even when the thread has no active run."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"threads.create",backend:"api",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,failureClass:null,failureRetryable:null}}]},route:{method:"POST",path:"/threads",tags:["Threads"],operationId:"threads.create",summary:"Create a thread",description:"Create a thread with an initial message and optionally wait for the agent response.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"threads.update",backend:"api",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",source:"api",createdAt:"2026-01-01T00:00:00.000Z",updatedAt:"2026-01-01T00:10:00.000Z"}}}]},route:{method:"PATCH",path:"/threads/{threadId}",tags:["Threads"],operationId:"threads.update",summary:"Update a thread",description:"Update a thread's status."}}},fork:{"~orpc":{errorMap:{},meta:{operationId:"threads.fork",backend:"api",pagination:"none",async:"sync",examples:[{name:"fork-from-message",input:{threadId:"22222222-2222-4222-8222-222222222222",messageId:"44444444-4444-4444-8444-444444444444"},output:{thread:{id:"66666666-6666-4666-8666-666666666666",projectId:"11111111-1111-4111-8111-111111111111",title:"API returning 500s (fork)",status:"regular",source:"api",createdAt:"2026-01-01T00:20:00.000Z",updatedAt:"2026-01-01T00:20:00.000Z"}}}]},route:{method:"POST",path:"/threads/{threadId}/fork",tags:["Threads"],operationId:"threads.fork",summary:"Fork a thread",description:"Fork a thread from a specific message, creating a new thread that copies messages up to that point.",successStatus:201}}},setVisibility:{"~orpc":{errorMap:{},meta:{operationId:"threads.setVisibility",backend:"api",pagination:"none",async:"sync",examples:[{name:"make-private",input:{threadId:"22222222-2222-4222-8222-222222222222",visibility:"private"},output:{thread:{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",title:"API returning 500s",status:"regular",source:"api",createdAt:"2026-01-01T00:00:00.000Z",updatedAt:"2026-01-01T00:30:00.000Z"},visibility:"private"}}]},route:{method:"PATCH",path:"/threads/{threadId}/visibility",tags:["Threads"],operationId:"threads.setVisibility",summary:"Set a thread's visibility",description:"Set a thread's visibility to private or organization."}}},createShareLink:{"~orpc":{errorMap:{},meta:{operationId:"threads.createShareLink",backend:"api",pagination:"none",async:"sync",examples:[{name:"create-share-link",input:{threadId:"22222222-2222-4222-8222-222222222222"},output:{share:{shareId:"55555555-5555-4555-8555-555555555555",threadId:"22222222-2222-4222-8222-222222222222",url:"https://app.sazabi.com/share/55555555-5555-4555-8555-555555555555",createdAt:"2026-01-01T00:40:00.000Z"}}}]},route:{method:"POST",path:"/threads/{threadId}/share",tags:["Threads"],operationId:"threads.createShareLink",summary:"Create a thread share link",description:"Create a public read-only share link for a thread's current messages.",successStatus:201}}},listShareLinks:{"~orpc":{errorMap:{},meta:{operationId:"threads.listShareLinks",backend:"api",pagination:"none",async:"sync",examples:[{name:"list-share-links",input:{threadId:"22222222-2222-4222-8222-222222222222"},output:{shares:[{shareId:"55555555-5555-4555-8555-555555555555",threadId:"22222222-2222-4222-8222-222222222222",url:"https://app.sazabi.com/share/55555555-5555-4555-8555-555555555555",createdAt:"2026-01-01T00:40:00.000Z"}]}}]},route:{method:"GET",path:"/threads/{threadId}/share",tags:["Threads"],operationId:"threads.listShareLinks",summary:"List thread share links",description:"List active public share links for a thread."}}},revokeShareLink:{"~orpc":{errorMap:{},meta:{operationId:"threads.revokeShareLink",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/threads/{threadId}/share/{shareId}",tags:["Threads"],operationId:"threads.revokeShareLink",summary:"Revoke a thread share link",description:"Revoke a public share link for a thread.",successStatus:204}}}},runs:{list:{"~orpc":{errorMap:{},meta:{operationId:"runs.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/runs",tags:["Runs"],operationId:"runs.list",summary:"List runs",description:"List deferred runs within one project."}}},listForThread:{"~orpc":{errorMap:{},meta:{operationId:"runs.listForThread",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/threads/{threadId}/runs",tags:["Runs"],operationId:"runs.listForThread",summary:"List runs for a thread",description:"List deferred runs for one thread."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"runs.get",backend:"api",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,failureClass:null,failureRetryable:null}},{name:"failed-retryable-run",input:{runId:"44444444-4444-4444-8444-444444444444"},output:{completed:!0,threadId:"22222222-2222-4222-8222-222222222222",runId:"44444444-4444-4444-8444-444444444444",status:"error",response:null,failureClass:"provider",failureRetryable:!0}}]},route:{method:"GET",path:"/runs/{runId}",tags:["Runs"],operationId:"runs.get",summary:"Get a run",description:"Get the current result for a deferred run by run ID."}}},cancel:{"~orpc":{errorMap:{},meta:{operationId:"runs.cancel",backend:"api",pagination:"none",async:"sync",examples:[{name:"cancel-processing-run",input:{runId:"33333333-3333-4333-8333-333333333333"},output:{success:!0}}]},route:{method:"POST",path:"/runs/{runId}/cancel",tags:["Runs"],operationId:"runs.cancel",summary:"Cancel a run",description:"Request cancellation of an in-flight run. Idempotent and best-effort: returns success even when the run has already reached a terminal status."}}}},pullRequests:{list:{"~orpc":{errorMap:{},meta:{operationId:"pullRequests.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/pull-requests",tags:["Pull Requests"],operationId:"pullRequests.list",summary:"List pull requests",description:"List pull requests that Sazabi opened, optionally filtered by status, repository, and requesting user."}}}},issues:{create:{"~orpc":{errorMap:{},meta:{operationId:"issues.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues",tags:["Issues"],operationId:"issues.create",summary:"Create an issue",description:"Create an issue in a project, returning an existing open issue when root-cause deduplication finds a match.",successStatus:201}}},list:{"~orpc":{errorMap:{},meta:{operationId:"issues.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/issues",tags:["Issues"],operationId:"issues.list",summary:"List issues",description:"List issues in a project, optionally filtered by status and severity."}}},search:{"~orpc":{errorMap:{},meta:{operationId:"issues.search",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/issues/search",tags:["Issues"],operationId:"issues.search",summary:"Search issues",description:"Search issues in a project by ranked text over name and description, status, and severity."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"issues.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/issues/{issueId}",tags:["Issues"],operationId:"issues.get",summary:"Get an issue",description:"Get a single issue by ID."}}},getRejectionContext:{"~orpc":{errorMap:{},meta:{operationId:"issues.getRejectionContext",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/issues/{issueId}/rejection",tags:["Issues"],operationId:"issues.getRejectionContext",summary:"Get issue rejection eligibility",description:"Get the rejection deadline, cycle quota, and billing effect for an issue."}}},reject:{"~orpc":{errorMap:{},meta:{operationId:"issues.reject",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues/{issueId}/reject",tags:["Issues"],operationId:"issues.reject",summary:"Reject an issue",description:"Permanently reject an eligible issue and correct one issue usage unit."}}},resolve:{"~orpc":{errorMap:{},meta:{operationId:"issues.resolve",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues/{issueId}/resolve",tags:["Issues"],operationId:"issues.resolve",summary:"Resolve an issue",description:"Resolve an open issue."}}},ignore:{"~orpc":{errorMap:{},meta:{operationId:"issues.ignore",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues/{issueId}/ignore",tags:["Issues"],operationId:"issues.ignore",summary:"Ignore an issue",description:"Ignore an open issue."}}},reopen:{"~orpc":{errorMap:{},meta:{operationId:"issues.reopen",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues/{issueId}/reopen",tags:["Issues"],operationId:"issues.reopen",summary:"Reopen an issue",description:"Reopen a resolved or ignored issue."}}},reassignAndReopen:{"~orpc":{errorMap:{},meta:{operationId:"issues.reassignAndReopen",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues/{issueId}/reassign-and-reopen",tags:["Issues"],operationId:"issues.reassignAndReopen",summary:"Reassign and reopen an issue",description:"Atomically reassign a resolved or ignored issue to an active component and reopen it."}}},mute:{"~orpc":{errorMap:{},meta:{operationId:"issues.mute",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues/{issueId}/mute",tags:["Issues"],operationId:"issues.mute",summary:"Mute an issue",description:"Mute an issue, suppressing future re-fires without changing status."}}},unmute:{"~orpc":{errorMap:{},meta:{operationId:"issues.unmute",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues/{issueId}/unmute",tags:["Issues"],operationId:"issues.unmute",summary:"Unmute an issue",description:"Unmute an issue, preserving its current status."}}}},workItems:{create:{"~orpc":{errorMap:{},meta:{operationId:"work-items.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/work-items",tags:["Work Items"],operationId:"work-items.create",summary:"Create a work item (deprecated)",description:"Deprecated alias for `POST /tasks` (create a task); removed in v2.0 (2027-03-01). Create a work item (e.g. a Linear issue) in a connected issue tracker, attributing the write to the requesting user.",successStatus:201,deprecated:!0}}},comment:{"~orpc":{errorMap:{},meta:{operationId:"work-items.comment",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/work-items/{itemId}/comment",tags:["Work Items"],operationId:"work-items.comment",summary:"Comment on a work item (deprecated)",description:"Deprecated alias for `POST /tasks/{taskId}/comment` (comment on a task); removed in v2.0 (2027-03-01). Add a comment to an existing work item.",deprecated:!0}}},transition:{"~orpc":{errorMap:{},meta:{operationId:"work-items.transition",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/work-items/{itemId}/transition",tags:["Work Items"],operationId:"work-items.transition",summary:"Transition a work item (deprecated)",description:"Deprecated alias for `POST /tasks/{taskId}/transition` (transition a task); removed in v2.0 (2027-03-01). Move a work item to a target workflow state.",deprecated:!0}}}},webhooks:{list:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/webhooks",tags:["Webhooks"],operationId:"webhooks.list",summary:"List webhook endpoints",description:"List webhook endpoints in the organization"}}},get:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/webhooks/{webhookId}",tags:["Webhooks"],operationId:"webhooks.get",summary:"Get a webhook endpoint",description:"Get a webhook endpoint and its subscriptions"}}},create:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/webhooks",tags:["Webhooks"],operationId:"webhooks.create",summary:"Create a webhook endpoint",description:"Create an endpoint and return its signing secret once",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PUT",path:"/webhooks/{webhookId}",tags:["Webhooks"],operationId:"webhooks.update",summary:"Update a webhook endpoint",description:"Update endpoint metadata, URL, or static authentication header"}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/webhooks/{webhookId}",tags:["Webhooks"],operationId:"webhooks.delete",summary:"Delete a webhook endpoint",description:"Tombstone an endpoint, its destinations, and its rules",successStatus:204}}},rotateSecret:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.rotateSecret",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/webhooks/{webhookId}/rotate-secret",tags:["Webhooks"],operationId:"webhooks.rotateSecret",summary:"Rotate a webhook signing secret",description:"Rotate and return the signing secret once"}}},enable:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.enable",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/webhooks/{webhookId}/enable",tags:["Webhooks"],operationId:"webhooks.enable",summary:"Enable a webhook endpoint",description:"Re-enable an endpoint disabled after delivery failures"}}},test:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.test",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/webhooks/{webhookId}/test",tags:["Webhooks"],operationId:"webhooks.test",summary:"Send a test webhook delivery",description:"Send a signed test envelope to an endpoint"}}},subscribe:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.subscribe",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/webhooks/{webhookId}/subscriptions",tags:["Webhooks"],operationId:"webhooks.subscribe",summary:"Subscribe a webhook",description:"Create a project notification rule for a webhook",successStatus:201}}},unsubscribe:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.unsubscribe",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/webhooks/{webhookId}/subscriptions/{subscriptionId}",tags:["Webhooks"],operationId:"webhooks.unsubscribe",summary:"Unsubscribe a webhook",description:"Remove a project notification rule for a webhook",successStatus:204}}},listDeliveries:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.listDeliveries",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/webhooks/{webhookId}/deliveries",tags:["Webhooks"],operationId:"webhooks.listDeliveries",summary:"List webhook deliveries",description:"List delivery history for an endpoint"}}}},billing:{getSummary:{"~orpc":{errorMap:{},meta:{operationId:"billing.getSummary",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/summary",tags:["Billing"],operationId:"billing.getSummary",summary:"Get billing summary",description:"Get a billing summary for the current organization, including plan, balance, and cycle information."}}},getUsage:{"~orpc":{errorMap:{},meta:{operationId:"billing.getUsage",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/usage",tags:["Billing"],operationId:"billing.getUsage",summary:"Get billing usage",description:"Get per-dimension usage breakdown for the current or previous billing cycle."}}},getAccruedUsageCharges:{"~orpc":{errorMap:{},meta:{operationId:"billing.getAccruedUsageCharges",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/usage-charges/accrued",tags:["Billing"],operationId:"billing.getAccruedUsageCharges",summary:"Get accrued usage charges",description:"Get usage charges accrued so far in the open billing cycle, priced under the cycle's plan terms. These settle on the cycle-end usage invoice."}}},listUsageInvoices:{"~orpc":{errorMap:{},meta:{operationId:"billing.listUsageInvoices",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/usage-invoices",tags:["Billing"],operationId:"billing.listUsageInvoices",summary:"List usage invoices",description:"List cycle-end usage invoices — the local settlement record, one per settled billing cycle, zero-total settlements included."}}},listTransactions:{"~orpc":{errorMap:{},meta:{operationId:"billing.listTransactions",backend:"api",pagination:"page",async:"sync",examples:[]},route:{method:"GET",path:"/billing/transactions",tags:["Billing"],operationId:"billing.listTransactions",summary:"List billing transactions",description:"List recent credit ledger transactions with pagination."}}},getAutoTopUp:{"~orpc":{errorMap:{},meta:{operationId:"billing.getAutoTopUp",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/auto-top-up",tags:["Billing"],operationId:"billing.getAutoTopUp",summary:"Get auto top-up settings",description:"Get the organization's credit auto top-up settings (trigger balance, top-up amount, cycle spending limit)."}}},updateAutoTopUp:{"~orpc":{errorMap:{},meta:{operationId:"billing.updateAutoTopUp",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PUT",path:"/billing/auto-top-up",tags:["Billing"],operationId:"billing.updateAutoTopUp",summary:"Update auto top-up settings",description:"Enable/disable and configure credit auto top-up. Requires a user credential with `billing:manage`."}}},purchaseCredits:{"~orpc":{errorMap:{},meta:{operationId:"billing.purchaseCredits",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/credits/purchase",tags:["Billing"],operationId:"billing.purchaseCredits",summary:"Purchase credits",description:"Purchase a one-time amount of credits against the saved payment method. Requires a user credential with `billing:manage` and a stable idempotency key."}}},listPlans:{"~orpc":{errorMap:{},meta:{operationId:"billing.listPlans",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/plans",tags:["Billing"],operationId:"billing.listPlans",summary:"List plans",description:"List the self-serve credit plans available for checkout, including the current plan."}}},previewPlanChange:{"~orpc":{errorMap:{},meta:{operationId:"billing.previewPlanChange",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/plan-change/preview",tags:["Billing"],operationId:"billing.previewPlanChange",summary:"Preview a plan change",description:"Preview the cost and effect of changing to a plan without applying it. Requires a user credential with `billing:manage`."}}},previewSubscriptionCancellation:{"~orpc":{errorMap:{},meta:{operationId:"billing.previewSubscriptionCancellation",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/subscription-cancellation/preview",tags:["Billing"],operationId:"billing.previewSubscriptionCancellation",summary:"Preview subscription cancellation",description:"Preview period-end subscription cancellation without changing billing state."}}},scheduleSubscriptionCancellation:{"~orpc":{errorMap:{},meta:{operationId:"billing.scheduleSubscriptionCancellation",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/subscription-cancellation",tags:["Billing"],operationId:"billing.scheduleSubscriptionCancellation",summary:"Schedule subscription cancellation",description:"Schedule cancellation at the end of the paid billing cycle."}}},resumeSubscriptionCancellation:{"~orpc":{errorMap:{},meta:{operationId:"billing.resumeSubscriptionCancellation",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/subscription-cancellation/resume",tags:["Billing"],operationId:"billing.resumeSubscriptionCancellation",summary:"Resume subscription renewal",description:"Resume renewal before a scheduled cancellation takes effect."}}},changePlan:{"~orpc":{errorMap:{},meta:{operationId:"billing.changePlan",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/plan-change",tags:["Billing"],operationId:"billing.changePlan",summary:"Change the plan",description:"Apply a plan upgrade or schedule a downgrade. Requires a user credential with `billing:manage`."}}},createCheckoutSession:{"~orpc":{errorMap:{},meta:{operationId:"billing.createCheckoutSession",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/checkout-session",tags:["Billing"],operationId:"billing.createCheckoutSession",summary:"Create a checkout session",description:"Create a hosted Stripe Checkout session for first-time subscribe from the terminal. Requires a user credential with `billing:manage`."}}},getCheckoutSessionStatus:{"~orpc":{errorMap:{},meta:{operationId:"billing.getCheckoutSessionStatus",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/checkout-session/{sessionId}",tags:["Billing"],operationId:"billing.getCheckoutSessionStatus",summary:"Get checkout session status",description:"Poll the completion status of a checkout session created by this organization."}}},createPortalSession:{"~orpc":{errorMap:{},meta:{operationId:"billing.createPortalSession",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/portal-session",tags:["Billing"],operationId:"billing.createPortalSession",summary:"Create a billing portal session",description:"Create a Stripe Customer Portal session for updating the payment method. Requires a user credential with `billing:manage`."}}},getPaymentMethod:{"~orpc":{errorMap:{},meta:{operationId:"billing.getPaymentMethod",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/payment-method",tags:["Billing"],operationId:"billing.getPaymentMethod",summary:"Get the payment method",description:"Get a summary of the organization's saved payment method (brand and last 4 digits)."}}}},tasks:{list:{"~orpc":{errorMap:{},meta:{operationId:"tasks.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/tasks",tags:["Onboarding Tasks"],operationId:"tasks.list",summary:"List onboarding tasks",description:"List all onboarding and setup tasks for a project, including their current completion status and a description of what is required to complete each task."}}},skip:{"~orpc":{errorMap:{},meta:{operationId:"tasks.skip",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/tasks/{taskId}/skip",tags:["Onboarding Tasks"],operationId:"tasks.skip",summary:"Skip an onboarding task",description:"Record an organization-wide skip for an optional onboarding task. The skip is shared across surfaces and teammates; completing the task through any door still outranks a recorded skip. Idempotent — re-skipping keeps the original skip record."}}},unskip:{"~orpc":{errorMap:{},meta:{operationId:"tasks.unskip",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/tasks/{taskId}/unskip",tags:["Onboarding Tasks"],operationId:"tasks.unskip",summary:"Reopen a skipped onboarding task",description:"Remove the organization-wide skip record for an onboarding task, reopening it in every onboarding walk. Idempotent — unskipping a task that is not skipped is a no-op."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"tasks.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/tasks",tags:["Tasks"],operationId:"tasks.create",summary:"Create a task",description:"Create a task (e.g. a Linear issue) in a connected external tracker, attributing the write to the requesting user.",successStatus:201}}},comment:{"~orpc":{errorMap:{},meta:{operationId:"tasks.comment",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/tasks/{taskId}/comment",tags:["Tasks"],operationId:"tasks.comment",summary:"Comment on a task",description:"Add a comment to an existing task."}}},transition:{"~orpc":{errorMap:{},meta:{operationId:"tasks.transition",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/tasks/{taskId}/transition",tags:["Tasks"],operationId:"tasks.transition",summary:"Transition a task",description:"Move a task to a target workflow state."}}}},recommendations:{list:{"~orpc":{errorMap:{},meta:{operationId:"recommendations.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/recommendations",tags:["Recommendations"],operationId:"recommendations.list",summary:"List recommendations",description:"List a project's configuration recommendations (data sources, MCP connectors, sandbox CLIs, and integrations) with each item's live connection status."}}}},repos:{list:{"~orpc":{errorMap:{},meta:{operationId:"repos.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/repos",tags:["Repos"],operationId:"repos.list",summary:"List repositories",description:"List the repositories available to a project — every repository reachable through the organization's GitHub App installations, the caller's personal forge connections, and integrations — with each one's linked status."}}},add:{"~orpc":{errorMap:{},meta:{operationId:"repos.add",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/repos",tags:["Repos"],operationId:"repos.add",summary:"Link repositories to a project",description:"Link repositories to a project by access source id. Select only one access source per repository; re-linking an already-linked repository refreshes its selected access source."}}},remove:{"~orpc":{errorMap:{},meta:{operationId:"repos.remove",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/repos/{id}",tags:["Repos"],operationId:"repos.remove",summary:"Unlink a repository from a project",description:"Unlink a repository from a project by repository row id.",successStatus:204}}}},components:{list:{"~orpc":{errorMap:{},meta:{operationId:"components.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/components",tags:["Components"],operationId:"components.list",summary:"List components",description:"List status page components in a project."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"components.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/components/{componentId}",tags:["Components"],operationId:"components.get",summary:"Get a component",description:"Get a single component by ID."}}},register:{"~orpc":{errorMap:{},meta:{operationId:"components.register",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components",tags:["Components"],operationId:"components.register",summary:"Register a component",description:"Register a status page component in a project, or refresh an existing active component with the same name."}}},deregister:{"~orpc":{errorMap:{},meta:{operationId:"components.deregister",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/{componentId}/deregister",tags:["Components"],operationId:"components.deregister",summary:"Deregister a component",description:"Withdraw this credential's component observation, or — for a human caller — preview the deregistration and confirm it by resubmitting with the previewed componentRevisions."}}},rename:{"~orpc":{errorMap:{},meta:{operationId:"components.rename",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/{componentId}/rename",tags:["Components"],operationId:"components.rename",summary:"Rename a component",description:"Rename an active component while reserving its previous exact name as an alias."}}},assignTeam:{"~orpc":{errorMap:{},meta:{operationId:"components.assignTeam",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PUT",path:"/components/{componentId}/team",tags:["Components"],operationId:"components.assignTeam",summary:"Assign a component to a team",description:"Assign a component to an owning team, reassign it, or unassign it. A component is owned by at most one team."}}},reactivationPreview:{"~orpc":{errorMap:{},meta:{operationId:"components.reactivationPreview",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/{componentId}/reactivation/preview",tags:["Components"],operationId:"components.reactivationPreview",summary:"Preview a component reactivation",description:"Preview unchanged deregistration-owned dependents that remain eligible for explicit reactivation."}}},reactivate:{"~orpc":{errorMap:{},meta:{operationId:"components.reactivate",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/{componentId}/reactivate",tags:["Components"],operationId:"components.reactivate",summary:"Reactivate a component",description:"Reactivate an inactive canonical component and only the explicitly selected eligible dependents. Prior rules, automations, and relationships stay detached unless explicitly selected."}}},mergePreview:{"~orpc":{errorMap:{},meta:{operationId:"components.mergePreview",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/merge/preview",tags:["Components"],operationId:"components.mergePreview",summary:"Preview a component merge",description:"Preview one-hop redirects, historical preservation, operational rebinding, topology contraction, and policy dispositions for component consolidation."}}},merge:{"~orpc":{errorMap:{},meta:{operationId:"components.merge",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/merge",tags:["Components"],operationId:"components.merge",summary:"Merge a component",description:"Consolidate a source into an active terminal target without rewriting historical issue or observation attribution."}}},relationships:{list:{"~orpc":{errorMap:{},meta:{operationId:"components.relationships.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/components/relationships",tags:["Components"],operationId:"components.relationships.list",summary:"List component relationships",description:"List active or historical component topology edges."}}},preview:{"~orpc":{errorMap:{},meta:{operationId:"components.relationships.preview",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/relationships/preview",tags:["Components"],operationId:"components.relationships.preview",summary:"Preview a component relationship change",description:"Preview descendant-scoped notification and automation impact for a topology change."}}},add:{"~orpc":{errorMap:{},meta:{operationId:"components.relationships.add",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/relationships",tags:["Components"],operationId:"components.relationships.add",summary:"Add a component relationship",description:"Add a confirmed, tenant-safe component topology edge."}}},remove:{"~orpc":{errorMap:{},meta:{operationId:"components.relationships.remove",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/relationships/remove",tags:["Components"],operationId:"components.relationships.remove",summary:"Remove a component relationship",description:"Historically end a confirmed component topology edge."}}}},incidents:{list:{"~orpc":{errorMap:{},meta:{operationId:"components.incidents.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/status-incidents",tags:["Components"],operationId:"components.incidents.list",summary:"List status-page issues",description:"List status-page issues in a project."}}}},timeline:{"~orpc":{errorMap:{},meta:{operationId:"components.timeline",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/components/{componentId}/timeline",tags:["Components"],operationId:"components.timeline",summary:"Get a component status timeline",description:"Get the dense status timeline and incidents for a component over a time window."}}}}}});var xb="https://api.sazabi.com",cx="https://api.platform.sazabi.com",lx="sazabi-cli",F0="urn:ietf:params:oauth:grant-type:device_code",ux=(e)=>{let t=qd(new op(ix,{url:B0(e.apiBaseUrl??xb),headers:async()=>{let s=new Headers({authorization:`Bearer ${await e.credentialProvider.getToken()}`});if(e.clientSource)s.set("x-sazabi-client-source",e.clientSource);if(e.clientVersion)s.set("x-sazabi-client-version",e.clientVersion);if(e.sandboxActorDescriptor)s.set("x-sazabi-sandbox-actor",e.sandboxActorDescriptor);return s},fetch:e.fetch,customErrorResponseBodyDecoder:(s,c)=>{let l=H0(s);if(!l)return null;return new Ye(l.code,{message:l.message,status:c.status,data:{...l.details,operationId:l.operationId,missingContext:l.missingContext,...l.reason!==void 0?{reason:l.reason}:{},...l.entitlementId!==void 0?{entitlementId:l.entitlementId}:{},...l.planSlug!==void 0?{planSlug:l.planSlug}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.current!==void 0?{current:l.current}:{},...l.actionPath!==void 0?{actionPath:l.actionPath}:{},...l.retryAfterSeconds!==void 0?{retryAfterSeconds:l.retryAfterSeconds}:{},...l.issues!==void 0?{issues:l.issues}:{},...l.diagnostics!==void 0?{diagnostics:l.diagnostics}:{},...l.currentRevision!==void 0?{currentRevision:l.currentRevision}:{}}})}})),n=QO({raw:t,credentialProvider:e.credentialProvider,fetch:e.fetch,apiBaseUrl:e.apiBaseUrl??xb,intakeBaseUrl:e.intakeBaseUrl,tailBaseUrl:e.tailBaseUrl}),r=KO({credentialProvider:e.credentialProvider,fetch:e.fetch,apiBaseUrl:e.apiBaseUrl??xb,clientSource:e.clientSource,clientVersion:e.clientVersion}),o=async(s,c)=>t.tasks.create(await Q(e.credentialProvider,s,c)),i=async(s,c)=>t.tasks.comment(await Q(e.credentialProvider,s,c)),a=async(s,c)=>t.tasks.transition(await Q(e.credentialProvider,s,c));return{raw:t,me:async()=>t.me({}),artifacts:{list:async(s={})=>t.artifacts.list(await U(e.credentialProvider,s)),listIssueArtifacts:async(s)=>t.artifacts.listIssueArtifacts(s),get:async(s)=>t.artifacts.get(await U(e.credentialProvider,s)),download:async(s)=>t.artifacts.download(await U(e.credentialProvider,s)),delete:async(s)=>t.artifacts.delete(await U(e.credentialProvider,s))},automations:{list:async(s={})=>t.automations.list(await U(e.credentialProvider,s)),get:async(s)=>t.automations.get(await U(e.credentialProvider,s)),create:async(s)=>t.automations.create(await U(e.credentialProvider,s)),update:async(s)=>t.automations.update(await U(e.credentialProvider,s)),enable:async(s)=>t.automations.enable(await U(e.credentialProvider,s)),disable:async(s)=>t.automations.disable(await U(e.credentialProvider,s)),delete:async(s)=>t.automations.delete(await U(e.credentialProvider,s)),runs:{list:async(s)=>t.automations.runs.list(await U(e.credentialProvider,s)),get:async(s)=>t.automations.runs.get(await U(e.credentialProvider,s)),logs:async(s)=>t.automations.runs.logs(await U(e.credentialProvider,s))}},automationTemplates:{list:()=>t.automationTemplates.list({})},dashboards:{list:async(s={})=>t.dashboards.list(await Un(e.credentialProvider,s,"dashboards.list")),get:async(s)=>t.dashboards.get(await Un(e.credentialProvider,s,"dashboards.get")),validate:async(s)=>t.dashboards.validate(await Un(e.credentialProvider,s,"dashboards.validate")),create:async(s)=>t.dashboards.create(await Un(e.credentialProvider,s,"dashboards.create")),update:async(s)=>t.dashboards.update(await Un(e.credentialProvider,s,"dashboards.update")),render:async(s)=>t.dashboards.render(await Un(e.credentialProvider,s,"dashboards.render")),delete:async(s)=>t.dashboards.delete(await Un(e.credentialProvider,s,"dashboards.delete"))},logs:{...n,ask:async(s)=>t.logs.ask(await U(e.credentialProvider,s)),executeQuery:async(s)=>t.logs.executeQuery(await Un(e.credentialProvider,s,"logs.executeQuery"))},onboarding:{getState:async(s={})=>t.onboarding.getState(await lo(e.credentialProvider,await U(e.credentialProvider,s))),skipSampleIssue:async(s)=>t.onboarding.skipSampleIssue(await lo(e.credentialProvider,s??{})),skipIntegration:async(s)=>t.onboarding.skipIntegration(await ax(e.credentialProvider,s)),skipGithubAppInstallation:async(s)=>t.onboarding.skipGithubAppInstallation(await ax(e.credentialProvider,s??{})),continueWithFree:async(s)=>t.onboarding.continueWithFree(await lo(e.credentialProvider,s??{})),ensureDefaultProject:async(s)=>t.onboarding.ensureDefaultProject(await lo(e.credentialProvider,s??{})),completeSampleIssue:async(s)=>t.onboarding.completeSampleIssue(await lo(e.credentialProvider,s??{})),finish:async(s)=>t.onboarding.finish(s)},organizations:{list:async()=>t.organizations.list({}),get:async(s)=>t.organizations.get(s),create:async(s)=>t.organizations.create(s),update:async(s)=>t.organizations.update(await Q(e.credentialProvider,s,"organizations.update"))},members:{list:async(s={})=>t.members.list(await Q(e.credentialProvider,s,"members.list")),updateRole:async(s)=>t.members.updateRole(await Q(e.credentialProvider,s,"members.updateRole")),remove:async(s)=>{let c=await Q(e.credentialProvider,s,"members.remove");return t.members.remove({params:{member:c.member},query:{organizationId:c.organizationId}})},invite:async(s)=>t.members.invite(await Q(e.credentialProvider,s,"members.invite")),listInvitations:async(s={})=>t.members.listInvitations(await Q(e.credentialProvider,s,"members.listInvitations")),revokeInvitation:async(s)=>{let c=await Q(e.credentialProvider,s,"members.revokeInvitation");return t.members.revokeInvitation({params:{invitationId:c.invitationId},query:{organizationId:c.organizationId}})}},teams:{list:async(s={})=>t.teams.list(await Q(e.credentialProvider,s,"teams.list")),create:async(s)=>t.teams.create(await Q(e.credentialProvider,s,"teams.create")),update:async(s)=>t.teams.update(await Q(e.credentialProvider,s,"teams.update")),delete:async(s)=>{let c=await Q(e.credentialProvider,s,"teams.delete");return t.teams.delete({params:{teamId:c.teamId},query:{organizationId:c.organizationId}})},addMember:async(s)=>t.teams.addMember(await Q(e.credentialProvider,s,"teams.addMember")),removeMember:async(s)=>{let c=await Q(e.credentialProvider,s,"teams.removeMember");return t.teams.removeMember({params:{teamId:c.teamId,userId:c.userId},query:{organizationId:c.organizationId}})},listMembers:async(s)=>t.teams.listMembers(await Q(e.credentialProvider,s,"teams.listMembers"))},publicKeys:{list:async(s={})=>t.publicKeys.list(await U(e.credentialProvider,s)),get:async(s)=>t.publicKeys.get(await U(e.credentialProvider,s)),ensureLogForwarding:async(s={})=>t.publicKeys.ensureLogForwarding(await U(e.credentialProvider,s)),update:async(s)=>t.publicKeys.update(await U(e.credentialProvider,s)),deactivate:async(s)=>{let c=await U(e.credentialProvider,s);return t.publicKeys.deactivate({params:{keyId:c.keyId},query:{projectId:c.projectId}})}},secretKeys:{list:async(s={})=>t.secretKeys.list(await Q(e.credentialProvider,s,"secretKeys.list")),get:async(s)=>t.secretKeys.get(await Q(e.credentialProvider,s,"secretKeys.get")),create:async(s)=>t.secretKeys.create(await Q(e.credentialProvider,s,"secretKeys.create")),update:async(s)=>t.secretKeys.update(await Q(e.credentialProvider,s,"secretKeys.update")),delete:async(s)=>{let{organizationId:c}=await Q(e.credentialProvider,s,"secretKeys.delete");await t.secretKeys.delete({params:{keyId:s.keyId},query:{organizationId:c}})}},search:{threads:async(s)=>t.search.threads(await U(e.credentialProvider,s)),messages:async(s)=>t.search.messages(await U(e.credentialProvider,s))},projects:{list:async(s={})=>t.projects.list(await G0(e.credentialProvider,s)),get:async(s)=>t.projects.get(s),create:async(s)=>t.projects.create(await Q(e.credentialProvider,s,"projects.create")),update:async(s)=>t.projects.update(s),delete:async(s)=>t.projects.delete(s)},messages:{list:async(s)=>t.messages.list(s),append:async(s)=>sx(t,await t.messages.append(V0(s)))},threads:{list:async(s={})=>t.threads.list(await K0(e.credentialProvider,s)),get:async(s)=>t.threads.get(s),getStatus:async(s)=>t.threads.getStatus(s),stop:async(s)=>t.threads.stop(s),create:async(s)=>sx(t,await t.threads.create(await W0(e.credentialProvider,s))),update:async(s)=>t.threads.update(s),fork:async(s)=>t.threads.fork(s),setVisibility:async(s)=>t.threads.setVisibility(s),createShareLink:async(s)=>t.threads.createShareLink(s),listShareLinks:async(s)=>t.threads.listShareLinks(s),revokeShareLink:async(s)=>t.threads.revokeShareLink(s),stream:async(s)=>r.streamThread(s)},runs:{list:async(s={})=>t.runs.list(await q0(e.credentialProvider,s)),listForThread:async(s)=>t.runs.listForThread(s),get:async(s)=>t.runs.get(s),cancel:async(s)=>t.runs.cancel(s),stream:async(s)=>r.streamRun(s)},logSources:{listProviders:async()=>t.logSources.listProviders({}),list:async(s={})=>t.logSources.list(await U(e.credentialProvider,s)),get:async(s)=>t.logSources.get(s),create:async(s)=>t.logSources.create(await U(e.credentialProvider,s)),update:async(s)=>t.logSources.update(s),delete:async(s)=>t.logSources.delete(s),verify:async(s)=>t.logSources.verify(s)},logStreams:{list:async(s)=>t.logStreams.list(s),get:async(s)=>t.logStreams.get(s),create:async(s)=>t.logStreams.create(s),update:async(s)=>t.logStreams.update(s),delete:async(s)=>t.logStreams.delete(s),reassign:async(s)=>t.logStreams.reassign(s),createBatch:async(s)=>t.logStreams.createBatch(s),volumeStats:async(s)=>t.logStreams.volumeStats(s)},connectedAccounts:{beginConnect:async(s)=>t.connectedAccounts.beginConnect(await Q(e.credentialProvider,s,"connectedAccounts.beginConnect")),getConnectAttempt:async(s)=>t.connectedAccounts.getConnectAttempt(await Q(e.credentialProvider,s,"connectedAccounts.getConnectAttempt")),list:async(s={})=>t.connectedAccounts.list(await Q(e.credentialProvider,s,"connectedAccounts.list")),disconnect:async(s)=>t.connectedAccounts.disconnect(await Q(e.credentialProvider,s,"connectedAccounts.disconnect"))},integrations:{listProviders:async(s={})=>t.integrations.listProviders(await Q(e.credentialProvider,s,"integrations.listProviders")),listConnections:async(s={})=>t.integrations.listConnections(await Q(e.credentialProvider,s,"integrations.listConnections")),getConnection:async(s)=>t.integrations.getConnection(await Q(e.credentialProvider,s,"integrations.getConnection")),createConnection:async(s)=>t.integrations.createConnection(await Q(e.credentialProvider,s,"integrations.createConnection")),beginConnect:async(s)=>t.integrations.beginConnect(await Q(e.credentialProvider,s,"integrations.beginConnect")),getConnectAttempt:async(s)=>t.integrations.getConnectAttempt(await Q(e.credentialProvider,s,"integrations.getConnectAttempt")),disconnectConnection:async(s)=>t.integrations.disconnectConnection(await Q(e.credentialProvider,s,"integrations.disconnectConnection")),updateConnectionCredentials:async(s)=>t.integrations.updateConnectionCredentials(await Q(e.credentialProvider,s,"integrations.updateConnectionCredentials")),createSlackChannel:async(s)=>t.integrations.createSlackChannel(await Q(e.credentialProvider,s,"integrations.createSlackChannel")),getActiveCLIAttempt:async(s)=>t.integrations.getActiveCLIAttempt(await Q(e.credentialProvider,s,"integrations.getActiveCLIAttempt")),getLinearAutomationConfiguration:async(s)=>t.integrations.getLinearAutomationConfiguration(await Q(e.credentialProvider,s,"integrations.getLinearAutomationConfiguration")),updateLinearAutomationConfiguration:async(s)=>t.integrations.updateLinearAutomationConfiguration(await Q(e.credentialProvider,s,"integrations.updateLinearAutomationConfiguration")),getOrganizationExternalIdentityJitPolicy:async(s={})=>t.integrations.getOrganizationExternalIdentityJitPolicy(await Q(e.credentialProvider,s,"integrations.getOrganizationExternalIdentityJitPolicy")),updateOrganizationExternalIdentityJitPolicy:async(s)=>t.integrations.updateOrganizationExternalIdentityJitPolicy(await Q(e.credentialProvider,s,"integrations.updateOrganizationExternalIdentityJitPolicy")),getConnectionExternalIdentityJitPolicy:async(s)=>t.integrations.getConnectionExternalIdentityJitPolicy(await Q(e.credentialProvider,s,"integrations.getConnectionExternalIdentityJitPolicy")),updateConnectionExternalIdentityJitPolicy:async(s)=>t.integrations.updateConnectionExternalIdentityJitPolicy(await Q(e.credentialProvider,s,"integrations.updateConnectionExternalIdentityJitPolicy")),getMicrosoftTeamsAdminConsent:async(s)=>t.integrations.getMicrosoftTeamsAdminConsent(await Q(e.credentialProvider,s,"integrations.getMicrosoftTeamsAdminConsent")),getSlackConfiguration:async(s)=>t.integrations.getSlackConfiguration(await Q(e.credentialProvider,s,"integrations.getSlackConfiguration")),updateSlackConfiguration:async(s)=>t.integrations.updateSlackConfiguration(await Q(e.credentialProvider,s,"integrations.updateSlackConfiguration")),listSlackChannelProjectMappings:async(s)=>t.integrations.listSlackChannelProjectMappings(await Q(e.credentialProvider,s,"integrations.listSlackChannelProjectMappings")),setSlackChannelProjectMapping:async(s)=>t.integrations.setSlackChannelProjectMapping(await Q(e.credentialProvider,s,"integrations.setSlackChannelProjectMapping")),deleteSlackChannelProjectMapping:async(s)=>t.integrations.deleteSlackChannelProjectMapping(await Q(e.credentialProvider,s,"integrations.deleteSlackChannelProjectMapping"))},mcpConnectors:{list:async(s={})=>t.mcpConnectors.list(await U(e.credentialProvider,s)),get:async(s)=>t.mcpConnectors.get(await U(e.credentialProvider,s)),details:async(s)=>t.mcpConnectors.details(await U(e.credentialProvider,s)),listProviders:async()=>t.mcpConnectors.listProviders({}),search:async(s={})=>t.mcpConnectors.search(await U(e.credentialProvider,s)),describe:async(s)=>t.mcpConnectors.describe(await U(e.credentialProvider,s)),call:async(s)=>t.mcpConnectors.call(await U(e.credentialProvider,s)),create:async(s)=>t.mcpConnectors.create(await U(e.credentialProvider,s)),update:async(s)=>t.mcpConnectors.update(await U(e.credentialProvider,s)),disconnect:async(s)=>{await t.mcpConnectors.disconnect(await U(e.credentialProvider,s))},setReadOnly:async(s)=>t.mcpConnectors.setReadOnly(await U(e.credentialProvider,s)),beginOAuthInstall:async(s)=>t.mcpConnectors.beginOAuthInstall(await U(e.credentialProvider,s)),getOAuthInstallAttempt:async(s)=>t.mcpConnectors.getOAuthInstallAttempt(await U(e.credentialProvider,s))},sandboxEnvironmentVariables:{delete:async(s)=>t.sandboxEnvironmentVariables.delete(await U(e.credentialProvider,s)),get:async(s)=>t.sandboxEnvironmentVariables.get(await U(e.credentialProvider,s)),list:async(s={})=>t.sandboxEnvironmentVariables.list(await U(e.credentialProvider,s)),upsert:async(s)=>t.sandboxEnvironmentVariables.upsert(await U(e.credentialProvider,s))},sandboxInitScript:{get:async(s={})=>t.sandboxInitScript.get(await U(e.credentialProvider,s)),upsert:async(s)=>t.sandboxInitScript.upsert(await U(e.credentialProvider,s)),delete:async(s={})=>t.sandboxInitScript.delete(await U(e.credentialProvider,s))},sandboxClis:{delete:async(s)=>t.sandboxClis.deleteCli(await U(e.credentialProvider,s)),listConnections:async(s={})=>t.sandboxClis.listConnections(await U(e.credentialProvider,s)),listTypes:async()=>t.sandboxClis.listTypes({}),test:async(s)=>t.sandboxClis.testCli(await U(e.credentialProvider,s)),upsert:async(s)=>t.sandboxClis.upsertCli(await U(e.credentialProvider,s)),verify:async(s)=>t.sandboxClis.verify(await U(e.credentialProvider,s))},memory:{list:async(s={})=>t.memory.list(await U(e.credentialProvider,s)),get:async(s)=>t.memory.get(await U(e.credentialProvider,s)),put:async(s)=>t.memory.put(await U(e.credentialProvider,s)),create:async(s)=>t.memory.create(await U(e.credentialProvider,s)),update:async(s)=>t.memory.update(await U(e.credentialProvider,s)),search:async(s)=>t.memory.search(await U(e.credentialProvider,s)),delete:async(s)=>t.memory.delete(await U(e.credentialProvider,s))},supportTickets:{create:async(s)=>t.supportTickets.create(await U(e.credentialProvider,await Q(e.credentialProvider,s,"supportTickets.create"))),availability:async()=>t.supportTickets.availability({})},signalDefinitions:{list:async(s={})=>t.signalDefinitions.list(await U(e.credentialProvider,s)),get:async(s)=>t.signalDefinitions.get(await U(e.credentialProvider,s)),create:async(s)=>t.signalDefinitions.create(await U(e.credentialProvider,s)),update:async(s)=>t.signalDefinitions.update(await U(e.credentialProvider,s)),disable:async(s)=>t.signalDefinitions.disable(await U(e.credentialProvider,s)),delete:async(s)=>t.signalDefinitions.delete(await U(e.credentialProvider,s))},scripts:{list:async(s={})=>t.scripts.list(await U(e.credentialProvider,s)),get:async(s)=>t.scripts.get(await U(e.credentialProvider,s)),create:async(s)=>t.scripts.create(await U(e.credentialProvider,s)),update:async(s)=>t.scripts.update(await U(e.credentialProvider,s)),delete:async(s)=>t.scripts.delete(await U(e.credentialProvider,s))},issues:{create:async(s)=>t.issues.create(await U(e.credentialProvider,s)),list:async(s={})=>t.issues.list(await U(e.credentialProvider,s)),search:async(s={})=>t.issues.search(await U(e.credentialProvider,s)),get:async(s)=>t.issues.get(s),getRejectionContext:async(s)=>t.issues.getRejectionContext(s),reject:async(s)=>t.issues.reject(s),resolve:async(s)=>t.issues.resolve(s),ignore:async(s)=>t.issues.ignore(s),reopen:async(s)=>t.issues.reopen(s),mute:async(s)=>t.issues.mute(s),unmute:async(s)=>t.issues.unmute(s),reassignAndReopen:async(s)=>t.issues.reassignAndReopen(s)},workItems:{create:async(s)=>t.workItems.create(await Q(e.credentialProvider,s,"work-items.create")),comment:async(s)=>t.workItems.comment(await Q(e.credentialProvider,s,"work-items.comment")),transition:async(s)=>t.workItems.transition(await Q(e.credentialProvider,s,"work-items.transition"))},pullRequests:{list:async(s={})=>t.pullRequests.list(await U(e.credentialProvider,s))},components:{list:async(s={})=>t.components.list(await U(e.credentialProvider,s)),get:async(s)=>t.components.get(s),register:async(s)=>t.components.register(await U(e.credentialProvider,s)),deregister:async(s)=>t.components.deregister(s),rename:async(s)=>t.components.rename(s),assignTeam:async(s)=>t.components.assignTeam(s),reactivationPreview:async(s)=>t.components.reactivationPreview(s),reactivate:async(s)=>t.components.reactivate(s),mergePreview:async(s)=>t.components.mergePreview(await U(e.credentialProvider,s)),merge:async(s)=>t.components.merge(await U(e.credentialProvider,s)),relationships:{list:async(s={})=>t.components.relationships.list(await U(e.credentialProvider,s)),preview:async(s)=>t.components.relationships.preview(await U(e.credentialProvider,s)),add:async(s)=>t.components.relationships.add(await U(e.credentialProvider,s)),remove:async(s)=>t.components.relationships.remove(await U(e.credentialProvider,s))},incidents:{list:async(s={})=>t.components.incidents.list(await U(e.credentialProvider,s))},timeline:async(s)=>t.components.timeline(s)},billing:{getSummary:async(s={})=>t.billing.getSummary(await Q(e.credentialProvider,s,"billing.getSummary")),getUsage:async(s={})=>t.billing.getUsage(await Q(e.credentialProvider,s,"billing.getUsage")),getAccruedUsageCharges:async(s={})=>t.billing.getAccruedUsageCharges(await Q(e.credentialProvider,s,"billing.getAccruedUsageCharges")),listUsageInvoices:async(s={})=>t.billing.listUsageInvoices(await Q(e.credentialProvider,s,"billing.listUsageInvoices")),listTransactions:async(s={})=>t.billing.listTransactions(await Q(e.credentialProvider,s,"billing.listTransactions")),previewSubscriptionCancellation:async(s={})=>t.billing.previewSubscriptionCancellation(await Q(e.credentialProvider,s,"billing.previewSubscriptionCancellation")),scheduleSubscriptionCancellation:async(s={})=>t.billing.scheduleSubscriptionCancellation(await Q(e.credentialProvider,s,"billing.scheduleSubscriptionCancellation")),resumeSubscriptionCancellation:async(s={})=>t.billing.resumeSubscriptionCancellation(await Q(e.credentialProvider,s,"billing.resumeSubscriptionCancellation")),getAutoTopUp:async(s={})=>t.billing.getAutoTopUp(await Q(e.credentialProvider,s,"billing.getAutoTopUp")),updateAutoTopUp:async(s)=>t.billing.updateAutoTopUp(await Q(e.credentialProvider,s,"billing.updateAutoTopUp")),purchaseCredits:async(s)=>t.billing.purchaseCredits(await Q(e.credentialProvider,s,"billing.purchaseCredits")),listPlans:async(s={})=>t.billing.listPlans(await Q(e.credentialProvider,s,"billing.listPlans")),previewPlanChange:async(s)=>t.billing.previewPlanChange(await Q(e.credentialProvider,s,"billing.previewPlanChange")),changePlan:async(s)=>t.billing.changePlan(await Q(e.credentialProvider,s,"billing.changePlan")),createCheckoutSession:async(s)=>t.billing.createCheckoutSession(await Q(e.credentialProvider,s,"billing.createCheckoutSession")),getCheckoutSessionStatus:async(s)=>t.billing.getCheckoutSessionStatus(await Q(e.credentialProvider,s,"billing.getCheckoutSessionStatus")),createPortalSession:async(s={})=>t.billing.createPortalSession(await Q(e.credentialProvider,s,"billing.createPortalSession")),getPaymentMethod:async(s={})=>t.billing.getPaymentMethod(await Q(e.credentialProvider,s,"billing.getPaymentMethod"))},tasks:{list:async(s={})=>t.tasks.list(await Un(e.credentialProvider,s,"tasks.list")),skip:async(s)=>t.tasks.skip(await lo(e.credentialProvider,await U(e.credentialProvider,s))),unskip:async(s)=>t.tasks.unskip(await lo(e.credentialProvider,await U(e.credentialProvider,s))),create:async(s)=>o(s,"tasks.create"),comment:async(s)=>i(s,"tasks.comment"),transition:async(s)=>a(s,"tasks.transition")},recommendations:{list:async(s={})=>t.recommendations.list(await U(e.credentialProvider,s))},repos:{list:async(s={})=>t.repos.list(await U(e.credentialProvider,s)),add:async(s)=>t.repos.add(await U(e.credentialProvider,s)),remove:async(s)=>t.repos.remove(await U(e.credentialProvider,s))},notificationDeliveryRules:{list:async(s={})=>t.notificationDeliveryRules.list(await U(e.credentialProvider,s)),options:async(s={})=>t.notificationDeliveryRules.options(await U(e.credentialProvider,s)),create:async(s)=>t.notificationDeliveryRules.create(await U(e.credentialProvider,s)),update:async(s)=>t.notificationDeliveryRules.update(await U(e.credentialProvider,s)),delete:async(s)=>t.notificationDeliveryRules.delete(await U(e.credentialProvider,s))},taskCreationRules:{list:async(s={})=>t.taskCreationRules.list(await U(e.credentialProvider,s)),get:async(s)=>t.taskCreationRules.get(await U(e.credentialProvider,s)),create:async(s)=>t.taskCreationRules.create(await U(e.credentialProvider,s)),update:async(s)=>t.taskCreationRules.update(await U(e.credentialProvider,s)),delete:async(s)=>t.taskCreationRules.delete(await U(e.credentialProvider,s)),reorder:async(s)=>t.taskCreationRules.reorder(await U(e.credentialProvider,s))},notificationChannels:{getProject:async(s={})=>t.notificationChannels.getProject(await U(e.credentialProvider,s))},webhooks:{list:async()=>t.webhooks.list({}),get:async(s)=>t.webhooks.get(s),create:async(s)=>t.webhooks.create(s),update:async(s)=>t.webhooks.update(s),delete:async(s)=>t.webhooks.delete(s),rotateSecret:async(s)=>t.webhooks.rotateSecret(s),enable:async(s)=>t.webhooks.enable(s),test:async(s)=>t.webhooks.test(s),subscribe:async(s)=>t.webhooks.subscribe(await U(e.credentialProvider,s)),unsubscribe:async(s)=>t.webhooks.unsubscribe(s),listDeliveries:async(s)=>t.webhooks.listDeliveries(s)}}},Tb=async(e={})=>{let t=await mx(e.fetch)(dx(e.apiBaseUrl??cx,"/device/code"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:e.clientId??lx,...e.scope?{scope:e.scope}:{}})}),n=await t.json();if(!t.ok)throw Y0(n,t.status);let r=n;return{deviceCode:Xr(r.device_code,"device_code"),userCode:Xr(r.user_code,"user_code"),verificationUri:Xr(r.verification_uri,"verification_uri"),verificationUriComplete:Xr(r.verification_uri_complete,"verification_uri_complete"),expiresIn:Ab(r.expires_in,"expires_in"),interval:Ab(r.interval,"interval")}},_b=async(e)=>{let t=await mx(e.fetch)(dx(e.apiBaseUrl??cx,"/device/token"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:F0,device_code:e.deviceCode,client_id:e.clientId??lx})}),n=await t.json();if(t.ok){let o=n;return{status:"authorized",accessToken:Xr(o.access_token,"access_token"),tokenType:Xr(o.token_type,"token_type"),expiresIn:Ab(o.expires_in,"expires_in"),scope:typeof o.scope==="string"?o.scope:""}}let r=px(n);if(!r)throw Error(`Device authorization failed with status ${t.status}`);if(r.error==="authorization_pending")return{status:"pending"};if(r.error==="slow_down")return{status:"pending",interval:10};if(r.error==="access_denied")return{status:"denied",message:r.errorDescription};if(r.error==="expired_token"||r.error==="invalid_grant")return{status:"expired",message:r.errorDescription};throw Error(r.errorDescription)},B0=(e)=>{let t=e.replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`},dx=(e,t)=>`${e.replace(/\/+$/,"")}/api/auth${t}`,G0=async(e,t)=>Q(e,t,"projects.list"),lo=async(e,t)=>{let n=t.organizationId??await e.getOrganizationId?.();return n?{...t,organizationId:n}:t},Q=async(e,t,n)=>{let r=t.organizationId??await e.getOrganizationId?.();if(!r)throw new Ye("BAD_REQUEST",{message:"Organization ID is required",data:{operationId:n,missingContext:["organizationId"]},status:400});return{...t,organizationId:r}},ax=async(e,t)=>t.organizationId!==void 0?t:lo(e,await U(e,t)),U=async(e,t)=>{let n=t.projectId??await e.getProjectId?.();return n?{...t,projectId:n}:t},Un=async(e,t,n)=>{let r=t.projectId??await e.getProjectId?.();if(!r)throw new Ye("BAD_REQUEST",{message:"Project ID is required",data:{operationId:n,missingContext:["projectId"]},status:400});return{...t,projectId:r}},K0=async(e,t)=>{let n=t.projectId??await e.getProjectId?.();return n?{...t,projectId:n}:t},q0=async(e,t)=>{let n=t.projectId??await e.getProjectId?.();return n?{...t,projectId:n}:t},W0=async(e,t)=>{let n=t.projectId??await e.getProjectId?.();return n?{...t,projectId:n}:t},V0=(e)=>({threadId:e.threadId,message:e.message,wait:e.wait??!0,timeoutSeconds:e.timeoutSeconds??20,...e.automationId!==void 0?{automationId:e.automationId}:{}}),H0=(e)=>{if(!e||typeof e!=="object")return null;let t=e;if(typeof t.code!=="string"||typeof t.message!=="string"||typeof t.operationId!=="string")return null;return{code:t.code,message:t.message,operationId:t.operationId,missingContext:Array.isArray(t.missingContext)?t.missingContext.filter((n)=>typeof n==="string"):[],...typeof t.reason==="string"?{reason:t.reason}:{},...typeof t.entitlementId==="string"?{entitlementId:t.entitlementId}:{},...typeof t.planSlug==="string"||t.planSlug===null?{planSlug:t.planSlug}:{},...typeof t.limit==="boolean"||typeof t.limit==="string"||typeof t.limit==="number"||t.limit===null?{limit:t.limit}:{},...typeof t.current==="number"?{current:t.current}:{},...typeof t.actionPath==="string"?{actionPath:t.actionPath}:{},...typeof t.retryAfterSeconds==="number"?{retryAfterSeconds:t.retryAfterSeconds}:{},...Array.isArray(t.issues)?{issues:J0(t.issues)}:{},...Z0(t.details),...Array.isArray(t.diagnostics)?{diagnostics:t.diagnostics}:{},...typeof t.currentRevision==="number"?{currentRevision:t.currentRevision}:{}}},Z0=(e)=>{if(!e||typeof e!=="object"||Array.isArray(e))return{};let t=Object.fromEntries(Object.entries(e).filter((n)=>typeof n[1]==="string"));return Object.keys(t).length>0?{details:t}:{}},J0=(e)=>e.flatMap((t)=>{if(!t||typeof t!=="object")return[];let{path:n,message:r}=t;if(typeof r!=="string")return[];return[{message:r,path:Array.isArray(n)?n.filter((o)=>typeof o==="string"):[]}]}),px=(e)=>{if(!e||typeof e!=="object")return null;let t=e;if(typeof t.error!=="string"||typeof t.error_description!=="string")return null;return{error:t.error,errorDescription:t.error_description}},Y0=(e,t)=>{let n=px(e);return Error(n?.errorDescription??`Device authorization failed with status ${t}`)},mx=(e)=>e??globalThis.fetch,sx=(e,t)=>({result:t,poll:()=>e.runs.get({runId:t.runId}),waitForCompletion:async(n={})=>X0(e,t,n)}),X0=async(e,t,n)=>{if(t.completed)return t;let r=n.intervalMs??2000,o=Date.now(),i=t;while(!i.completed){if(n.timeoutMs!==void 0&&Date.now()-o>=n.timeoutMs)return i;await Q0(r),i=await e.runs.get({runId:i.runId})}return i},Q0=async(e)=>{await new Promise((t)=>globalThis.setTimeout(t,e))},Xr=(e,t)=>{if(typeof e==="string")return e;throw Error(`Expected '${t}' to be a string.`)},Ab=(e,t)=>{if(typeof e==="number")return e;throw Error(`Expected '${t}' to be a number.`)};var jb=L(()=>{vr();aw();qO();Ob();rx();Ob()});var Re=(e)=>({success:!0,value:e}),we=(e,t,n)=>({success:!1,error:e,...t!==void 0&&{statusCode:t},...n!==void 0&&{errorPayload:n}}),eF=(e)=>{if(e===void 0)return"NETWORK_ERROR";if(e===401)return"UNAUTHORIZED";if(e===403)return"FORBIDDEN";if(e===404)return"NOT_FOUND";if(e===402)return"PAYMENT_REQUIRED";if(e===429)return"TOO_MANY_REQUESTS";if(e>=500)return"SERVER_ERROR";return"REQUEST_FAILED"},tF="Your session has expired or is invalid. Run 'sazabi auth sign-in' to sign in again.",nF,gx="settings",hx=(e)=>{gx=e},oF=()=>nF[gx],f=(e,t,n,{signInOnUnauthorized:r=!0}={})=>{if(!e.success){let o=r&&e.statusCode===401?oF():`${t}: ${e.error}`;if(n)return h(e.errorPayload??{code:eF(e.statusCode),message:o,operationId:null});return g(o)}return e.value};var te=L(()=>{H();nF={settings:tF,environment:"Sazabi rejected the token in SAZABI_TOKEN: it's expired, invalid, or can't be used for this command. Set a valid token, or unset SAZABI_TOKEN and run 'sazabi auth sign-in' to sign in.",flag:"Sazabi rejected the token passed with --token: it's expired, invalid, or can't be used for this command. Pass a valid token, or drop --token and run 'sazabi auth sign-in' to sign in."}});var Mn=()=>Ed({moduleUrl:import.meta.url});var qa=L(()=>{H()});var rF="https://api.sazabi.com",iF,Rb,aF=30,sF=(e)=>new Promise((t)=>setTimeout(t,e)),w=async(e)=>{for(let t=0;;t+=1)try{return Re(await e())}catch(n){let r=cF(n),o=lF(n),i=r?.retryAfterSeconds;if(o===429&&t===0&&i!==void 0&&i<=aF&&process.env.SAZABI_NO_RETRY!=="1"){process.stderr.write(`Rate limited; retrying in ~${i}s…
|
|
116
|
+
`),...n?{id:n}:{}}),o()};return{line:(a)=>{if(a===""){i();return}if(a.startsWith(":"))return;let s=a.indexOf(":"),c=s===-1?a:a.slice(0,s),l=s===-1?"":a.slice(s+1),u=l.startsWith(" ")?l.slice(1):l;if(c==="event"){t=u||"message";return}if(c==="data"){r.push(u);return}if(c==="id"&&!u.includes("\x00"))n=u},flush:i}},D0=(e)=>{try{let t=WO.safeParse(JSON.parse(e));if(!t.success)return[];return t.data.data}catch{return[]}},HO=(e)=>e instanceof Error?e:Error(String(e)),ZO=(e)=>e instanceof Error&&e.name==="AbortError",$0=(e)=>e.message.startsWith("Authentication failed")||e.message.startsWith("Forbidden (")||e.message.startsWith("Wrong region (")||e.message.startsWith("Client error ("),N0=async(e,t,n,r={},o=3,i=1e4)=>{let a;for(let s=0;s<=o;s+=1){let c=new AbortController,l=globalThis.setTimeout(()=>c.abort(),i);try{let u=await e(t,{method:"POST",headers:{"content-type":"application/json",...r},body:JSON.stringify(n),signal:c.signal});if(u.ok)return;let d=await u.text();if(u.status===401||u.status===403)throw Error("Authentication failed. Check your public key.");if(u.status>=400&&u.status<500&&u.status!==429)throw Error(`Client error (${u.status}): ${d}`);a=Error(u.status===429?`Rate limited (429): ${d}`:`Server error (${u.status}): ${d}`)}catch(u){let d=u instanceof Error?u.message:String(u);if(d.startsWith("Authentication failed")||d.startsWith("Client error ("))throw u instanceof Error?u:Error(d);a=u instanceof Error&&u.name==="AbortError"?Error("Request timed out"):u instanceof Error?u:Error(String(u))}finally{globalThis.clearTimeout(l)}if(s<o)await nx(JO*2**s)}throw Error(`Failed after ${o+1} attempts: ${a?.message??"Unknown error"}`)},U0=(e)=>e.resourceLogs?.reduce((t,n)=>t+(n.scopeLogs?.reduce((r,o)=>r+(o.logRecords?.length??0),0)??0),0)??0,nx=async(e,t)=>{if(t?.aborted)return;await new Promise((n)=>{let r=globalThis.setTimeout(n,e);t?.addEventListener("abort",()=>{globalThis.clearTimeout(r),n()},{once:!0})})},ox=(e,t,n)=>new Ye("BAD_REQUEST",{message:t,data:{operationId:e,missingContext:n}});var Ob=L(()=>{vr();VO();lt();g0=k.object({projectId:k.string().uuid().optional().describe("Project to tail logs for. Auto-filled from CLI and SDK context when omitted."),filters:wb.optional().describe("Optional filters applied by the tail SSE service.")}),h0=k.object({publicKey:k.string().min(1).describe("Public key for intake auth. Create or list one via the public key endpoints."),logs:k.custom((e)=>typeof e==="object"&&e!==null).describe("OTLP logs export request payload to send to the intake service.")}),f0=k.object({forwardedCount:k.number().int().nonnegative().describe("Number of log records accepted by the intake request."),failedCount:k.number().int().nonnegative().describe("Number of log records rejected by the intake request.")}),b0=new Set(["15006","3010"])});var ix;var rx=L(()=>{ix={me:{"~orpc":{errorMap:{},meta:{operationId:"me.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/me",tags:["Auth"],operationId:"me.get",summary:"Get the current credential",description:"Return the identity and available context for the current credential."}}},automations:{list:{"~orpc":{errorMap:{},meta:{operationId:"automations.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/automations",tags:["Automations"],operationId:"automations.list",summary:"List automations",description:"List scheduled automations in a project, with run health and recent run stats."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"automations.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/automations/{automationId}",tags:["Automations"],operationId:"automations.get",summary:"Get an automation",description:"Get a single automation by ID."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"automations.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/automations",tags:["Automations"],operationId:"automations.create",summary:"Create an automation",description:"Create an automation: either a cron-driven project script (see scripts.create) or a signal investigation bound to a signal definition (see signalDefinitions.create).",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"automations.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/automations/{automationId}",tags:["Automations"],operationId:"automations.update",summary:"Update an automation",description:"Update an automation's name, description, or schedule. Does not change which script it runs."}}},enable:{"~orpc":{errorMap:{},meta:{operationId:"automations.enable",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/automations/{automationId}/enable",tags:["Automations"],operationId:"automations.enable",summary:"Enable an automation",description:"Enable an automation so it runs on its schedule."}}},disable:{"~orpc":{errorMap:{},meta:{operationId:"automations.disable",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/automations/{automationId}/disable",tags:["Automations"],operationId:"automations.disable",summary:"Disable an automation",description:"Disable an automation so it stops running on its schedule."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"automations.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/automations/{automationId}",tags:["Automations"],operationId:"automations.delete",description:"Soft-delete a custom automation.",successStatus:204}}},runs:{list:{"~orpc":{errorMap:{},meta:{operationId:"automations.runs.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/automations/{automationId}/runs",tags:["Automations"],operationId:"automations.runs.list",summary:"List automation runs",description:"List runs for an automation, most recent first."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"automations.runs.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/automations/{automationId}/runs/{runId}",tags:["Automations"],operationId:"automations.runs.get",summary:"Get an automation run",description:"Get a single automation run by ID."}}},logs:{"~orpc":{errorMap:{},meta:{operationId:"automations.runs.logs",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/automations/{automationId}/runs/{runId}/logs",tags:["Automations"],operationId:"automations.runs.logs",summary:"Get automation run logs",description:"Get the captured stdout/stderr for a single automation run, reading the full output from durable storage when the inline preview was truncated."}}}}},artifacts:{list:{"~orpc":{errorMap:{},meta:{operationId:"artifacts.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/artifacts",tags:["Artifacts"],operationId:"artifacts.list",summary:"List artifacts",description:"List artifacts in a project with optional issue and date filters"}}},listIssueArtifacts:{"~orpc":{errorMap:{},meta:{operationId:"artifacts.listIssueArtifacts",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/issues/{issueId}/artifacts",tags:["Artifacts"],operationId:"artifacts.listIssueArtifacts",summary:"List artifacts for an issue",description:"List artifacts referenced by an issue report"}}},get:{"~orpc":{errorMap:{},meta:{operationId:"artifacts.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/artifacts/{artifactId}",tags:["Artifacts"],operationId:"artifacts.get",summary:"Get an artifact",description:"Get public metadata for an artifact"}}},download:{"~orpc":{errorMap:{},meta:{operationId:"artifacts.download",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/artifacts/{artifactId}/download",tags:["Artifacts"],operationId:"artifacts.download",summary:"Download an artifact",description:"Create a short-lived signed URL for an artifact"}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"artifacts.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/artifacts/{artifactId}",tags:["Artifacts"],operationId:"artifacts.delete",summary:"Delete an artifact",description:"Soft-delete an artifact from a project",successStatus:204}}}},automationTemplates:{list:{"~orpc":{errorMap:{},meta:{operationId:"automationTemplates.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/automation-templates",tags:["Automations"],operationId:"automationTemplates.list",summary:"List automation templates",description:"List the published Sazabi automation template catalog. Metadata only; template content (script bodies and prompts) is not exposed."}}}},dashboards:{list:{"~orpc":{errorMap:{},meta:{operationId:"dashboards.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/dashboards",tags:["Dashboards"],operationId:"dashboards.list",summary:"List dashboards",description:"List the project's dashboards by most recent update: title, description, revision, timestamps, and your capabilities. Metadata only; never runs queries."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"dashboards.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/dashboards/{id}",tags:["Dashboards"],operationId:"dashboards.get",summary:"Get a dashboard",description:"Read a dashboard's current MDX source (with its edit base), metadata, and static file descriptors. Set includeFiles to also receive the static file contents, giving a copy you can edit and pass back to dashboards.update. Never runs queries."}}},validate:{"~orpc":{errorMap:{},meta:{operationId:"dashboards.validate",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/dashboards/validate",tags:["Dashboards"],operationId:"dashboards.validate",summary:"Validate a dashboard",description:"Check dashboard MDX, static files, layout, query shapes, and your permission without saving or running queries. Optional: create and update always validate too. Each diagnostic carries its source line and column, component id, code, and repair hint."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"dashboards.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/dashboards",tags:["Dashboards"],operationId:"dashboards.create",summary:"Create a dashboard",description:"Save a new dashboard from one MDX document (DashboardMeta, layout, and inline Log Query Spec v2 artifacts) plus any static files it references by path. Generate the id yourself and reuse it on retries: an identical retry returns the original result. The response's editBase goes into DashboardMeta before the next update.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"dashboards.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/dashboards/{id}",tags:["Dashboards"],operationId:"dashboards.update",summary:"Update a dashboard",description:"Save the next revision from a complete edited MDX document. DashboardMeta.editBase must name the revision you edited (from dashboards.get or the last create/update); if the dashboard changed since, the update is rejected with 409 and the current revision so you can reconcile."}}},render:{"~orpc":{errorMap:{},meta:{operationId:"dashboards.render",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/dashboards/{id}/render",tags:["Dashboards"],operationId:"dashboards.render",summary:"Render a dashboard",description:"Run a saved dashboard's queries over one time window and return its layout with one outcome per requested component (ok, empty, rejected, or error). Omit timeRange for the dashboard's default window, revision for the current one, and componentIds for every bound component."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"dashboards.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/dashboards/{id}",tags:["Dashboards"],operationId:"dashboards.delete",summary:"Delete a dashboard",description:"Delete a dashboard if expectedRevision is still its current revision. Deleting an already-deleted dashboard succeeds again."}}}},logs:{ask:{"~orpc":{errorMap:{},meta:{operationId:"logs.ask",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/logs/ask",tags:["Logs"],operationId:"logs.ask",summary:"Ask about logs",description:"Answer a natural-language question about one project's stored logs. Returns a plain-language `answer`, what was measured over which window (`explanation`, `window`), how exact and complete the numbers are (`meta`), and a `queryId`. An overview (what is broken, recent errors, what changed, what is new, with no specific topic, field or request for lines) is searched: its results are the window's kinds of log lines, with their counts in the window and the window before and example lines; every other question is measured exactly. With `results: true` it also returns the rows, value, table, series or kinds of log lines the answer was written from. Pass the `queryId` to `logs.executeQuery` to run the same query again over any window with no model involved. When nothing matches, `status` is `not_found` and the answer says so, with how the question was read."}}},executeQuery:{"~orpc":{errorMap:{},meta:{operationId:"logs.executeQuery",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/logs/queries/{queryId}/execute",tags:["Logs"],operationId:"logs.executeQuery",summary:"Run an earlier log query",description:"Run the query behind an earlier `logs.ask` answer again, by its `queryId`, with no model involved: over the window the answer covered or a new one, with a new `limit`, or narrowed to the log lines of one `group` of a table. Returns `results` without an answer, and a new `queryId` whose `parentId` is the one that was run. An unknown id is not found; asking the question again yields a new id."}}}},logSources:{listProviders:{"~orpc":{errorMap:{},meta:{operationId:"logSources.listProviders",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/log-sources/providers",tags:["Log Sources"],operationId:"logSources.listProviders",summary:"List log source providers",description:"List all supported log source providers with their setup modes and metadata requirements."}}},list:{"~orpc":{errorMap:{},meta:{operationId:"logSources.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/log-sources",tags:["Log Sources"],operationId:"logSources.list",summary:"List log sources",description:"List log sources within one project."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"logSources.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/log-sources",tags:["Log Sources"],operationId:"logSources.create",summary:"Create a log source",description:"Create a log source. Managed mode takes vendor credentials in `metadata`, validates them, and provisions delivery behind the log source. Connectionless mode mints the log source plus a keyed log stream and returns the intake key and endpoint card(s) to point the sender at.",successStatus:201}}},get:{"~orpc":{errorMap:{},meta:{operationId:"logSources.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/log-sources/{logSourceId}",tags:["Log Sources"],operationId:"logSources.get",summary:"Get a log source",description:"Get one log source by ID, including its log streams and their endpoint card(s)."}}},verify:{"~orpc":{errorMap:{},meta:{operationId:"logSources.verify",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/log-sources/{logSourceId}/verify",tags:["Log Sources"],operationId:"logSources.verify",summary:"Check saved log source credentials",description:"Verify the saved managed credentials without provisioning or changing vendor resources. Unknown and transient outcomes preserve previous evidence."}}},update:{"~orpc":{errorMap:{},meta:{operationId:"logSources.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/log-sources/{logSourceId}",tags:["Log Sources"],operationId:"logSources.update",summary:"Update a log source",description:"Update a log source: pause or resume ingestion across its log streams, and/or set or clear its ongoing auto-provisioning filter. Log sources cannot be renamed — their generated names are immutable."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"logSources.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/log-sources/{logSourceId}",tags:["Log Sources"],operationId:"logSources.delete",summary:"Delete a log source",description:"Delete a log source. Tombstones the log source and its log streams, deactivates their intake keys (already-ingested data is preserved with its attribution), and runs vendor-side cleanup for managed log sources when the provider supports it.",successStatus:200}}}},logStreams:{list:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/log-streams",tags:["Log Streams"],operationId:"logStreams.list",summary:"List log streams",description:"List the log streams that belong to a log source."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/log-streams",tags:["Log Streams"],operationId:"logStreams.create",summary:"Create a log stream",description:"Create a new log stream under a managed log source. Triggers async provisioning; poll the log stream to track it. Connectionless log sources are single-stream — create another log source instead.",successStatus:201}}},createBatch:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.createBatch",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/log-streams/batch",tags:["Log Streams"],operationId:"logStreams.createBatch",summary:"Batch-create log streams",description:"Create multiple log streams under a managed log source in one call. Every accepted stream gets a durable row immediately; provisioning happens asynchronously — poll each log stream to track it. API-created streams are always nameless, so there is no per-item rejection: every request item is either accepted (a row was created) or the whole call fails with a request-level error.",successStatus:201}}},volumeStats:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.volumeStats",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/log-streams/volume-stats",tags:["Log Streams"],operationId:"logStreams.volumeStats",description:"Get bytes, log count, intake rate, and last-received time for each log stream in a log source over a bounded window."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/log-streams/{streamId}",tags:["Log Streams"],operationId:"logStreams.get",summary:"Get a log stream",description:"Get one log stream by ID. Use to poll provisioning status."}}},update:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/log-streams/{streamId}",tags:["Log Streams"],operationId:"logStreams.update",summary:"Update a log stream",description:"Update a log stream: pause or resume its ingestion. Log streams cannot be renamed."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/log-streams/{streamId}",tags:["Log Streams"],operationId:"logStreams.delete",summary:"Delete a log stream",description:"Delete a log stream. Tombstones the log stream and deactivates its intake key. Deleting a connectionless log source's only log stream tombstones the log source too.",successStatus:200}}},reassign:{"~orpc":{errorMap:{},meta:{operationId:"logStreams.reassign",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/log-streams/{streamId}/reassign",tags:["Log Streams"],operationId:"logStreams.reassign",summary:"Reassign a log stream",description:"Move a log stream to a different connectionless log source in the same project. Preserves the stream's ID, intake key credential, and ingested data; rebinds the key's intake adapter to the target log source's provider so future data is processed as that provider's format.",successStatus:200}}}},connectedAccounts:{beginConnect:{"~orpc":{errorMap:{},meta:{operationId:"connectedAccounts.beginConnect",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/connected-accounts/connect",tags:["Connected Accounts"],operationId:"connectedAccounts.beginConnect",summary:"Begin a connected account connect flow",description:"Begin a browser connect flow for a connected-account provider. Returns a vendor URL to open in a browser and an attempt to poll; the vendor exchange completes server-side and no token ever reaches the caller.",successStatus:201}}},getConnectAttempt:{"~orpc":{errorMap:{},meta:{operationId:"connectedAccounts.getConnectAttempt",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/connected-accounts/connect/attempts/{attemptId}",tags:["Connected Accounts"],operationId:"connectedAccounts.getConnectAttempt",summary:"Get a connect attempt",description:"Poll a browser connect attempt started with `connectedAccounts.beginConnect`. Visible only to the user who began it."}}},list:{"~orpc":{errorMap:{},meta:{operationId:"connectedAccounts.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/connected-accounts",tags:["Connected Accounts"],operationId:"connectedAccounts.list",summary:"List connected accounts",description:"List the calling user's connected accounts for the organization."}}},disconnect:{"~orpc":{errorMap:{},meta:{operationId:"connectedAccounts.disconnect",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/connected-accounts/{provider}",tags:["Connected Accounts"],operationId:"connectedAccounts.disconnect",summary:"Disconnect a connected account",description:"Disconnect the calling user's connected account for a provider (soft delete)."}}}},integrations:{listProviders:{"~orpc":{errorMap:{},meta:{operationId:"integrations.listProviders",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/providers",tags:["Integrations"],operationId:"integrations.listProviders",summary:"List integration providers",description:"List supported integration providers and how many connections the organization has for each."}}},listConnections:{"~orpc":{errorMap:{},meta:{operationId:"integrations.listConnections",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connections",tags:["Integrations"],operationId:"integrations.listConnections",summary:"List integration connections",description:"List integration connections and their connection state for the organization."}}},getConnection:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getConnection",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connections/{connectionId}",tags:["Integrations"],operationId:"integrations.getConnection",summary:"Get an integration connection",description:"Get one integration connection by ID (non-secret config only)."}}},getLinearAutomationConfiguration:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getLinearAutomationConfiguration",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connections/{connectionId}/linear-automation",tags:["Integrations"],operationId:"integrations.getLinearAutomationConfiguration",summary:"Get Linear issue automation configuration",description:"Read the Linear team, project, and severity rules used to automatically create tickets for detected issues."}}},createConnection:{"~orpc":{errorMap:{},meta:{operationId:"integrations.createConnection",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/integrations/connections",tags:["Integrations"],operationId:"integrations.createConnection",summary:"Create an integration connection",description:"Create an integration connection for an api_key provider. Credentials are validated against the vendor, then stored encrypted.",successStatus:201}}},beginConnect:{"~orpc":{errorMap:{},meta:{operationId:"integrations.beginConnect",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/integrations/connect",tags:["Integrations"],operationId:"integrations.beginConnect",summary:"Begin a browser connect flow",description:"Begin a browser connect flow for an OAuth or app-installation provider. Returns a vendor URL to open in a browser and an attempt to poll; the vendor exchange completes server-side and no token ever reaches the caller.",successStatus:201}}},getConnectAttempt:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getConnectAttempt",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connect/attempts/{attemptId}",tags:["Integrations"],operationId:"integrations.getConnectAttempt",summary:"Get a connect attempt",description:"Poll a browser connect attempt started with `integrations.beginConnect`. Visible only to the user who began it."}}},getActiveCLIAttempt:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getActiveCLIAttempt",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connect/cli-attempt",tags:["Integrations"],operationId:"integrations.getActiveCLIAttempt",summary:"Get an active CLI connect attempt",description:"Return the newest pending, non-expired CLI-initiated connect attempt for the given provider, or null if none exists. Used by the dashboard to show a 'connection in progress from your terminal' message."}}},disconnectConnection:{"~orpc":{errorMap:{},meta:{operationId:"integrations.disconnectConnection",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/integrations/connections/{connectionId}",tags:["Integrations"],operationId:"integrations.disconnectConnection",summary:"Disconnect an integration connection",description:"Disconnect an integration connection (soft delete). Always succeeds regardless of stored credential state; cached vendor catalogs and routing derived from the connection are removed."}}},updateConnectionCredentials:{"~orpc":{errorMap:{},meta:{operationId:"integrations.updateConnectionCredentials",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/integrations/connections/{connectionId}/credentials",tags:["Integrations"],operationId:"integrations.updateConnectionCredentials",summary:"Update integration connection credentials",description:"Replace an api_key connection's credentials in place — the reconnect path for a connection that needs attention. Keeps connection-scoped configuration."}}},updateLinearAutomationConfiguration:{"~orpc":{errorMap:{},meta:{operationId:"integrations.updateLinearAutomationConfiguration",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/integrations/connections/{connectionId}/linear-automation",tags:["Integrations"],operationId:"integrations.updateLinearAutomationConfiguration",summary:"Update Linear issue automation configuration",description:"Set the Linear team, optional project, and per-severity ticket creation rules for detected issues."}}},getOrganizationExternalIdentityJitPolicy:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getOrganizationExternalIdentityJitPolicy",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/external-identity-jit-policy",tags:["Integrations"],operationId:"integrations.getOrganizationExternalIdentityJitPolicy",summary:"Get the organization external-identity JIT policy",description:"Read the organization's stored external-identity JIT policy."}}},updateOrganizationExternalIdentityJitPolicy:{"~orpc":{errorMap:{},meta:{operationId:"integrations.updateOrganizationExternalIdentityJitPolicy",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/integrations/external-identity-jit-policy",tags:["Integrations"],operationId:"integrations.updateOrganizationExternalIdentityJitPolicy",summary:"Update the organization external-identity JIT policy",description:"Enable or disable external-identity JIT across an organization."}}},getConnectionExternalIdentityJitPolicy:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getConnectionExternalIdentityJitPolicy",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connections/{connectionId}/external-identity-jit-policy",tags:["Integrations"],operationId:"integrations.getConnectionExternalIdentityJitPolicy",summary:"Get a connection external-identity JIT policy",description:"Read stored and effective JIT policy for one connection."}}},updateConnectionExternalIdentityJitPolicy:{"~orpc":{errorMap:{},meta:{operationId:"integrations.updateConnectionExternalIdentityJitPolicy",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/integrations/connections/{connectionId}/external-identity-jit-policy",tags:["Integrations"],operationId:"integrations.updateConnectionExternalIdentityJitPolicy",summary:"Update a connection external-identity JIT policy",description:"Enable or disable external-identity JIT for one connection."}}},getMicrosoftTeamsAdminConsent:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getMicrosoftTeamsAdminConsent",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connections/{connectionId}/microsoft-teams-admin-consent",tags:["Integrations"],operationId:"integrations.getMicrosoftTeamsAdminConsent",summary:"Get the Microsoft Teams tenant admin-consent status",description:"Read the recorded Microsoft tenant admin-consent status for a Teams connection, with a consent URL for retrying the grant."}}},getSlackConfiguration:{"~orpc":{errorMap:{},meta:{operationId:"integrations.getSlackConfiguration",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connections/{connectionId}/slack-configuration",tags:["Integrations"],operationId:"integrations.getSlackConfiguration",summary:"Get Slack connection configuration",description:"Read Slack connection configuration (default project, automatic responses, acknowledgement message)."}}},updateSlackConfiguration:{"~orpc":{errorMap:{},meta:{operationId:"integrations.updateSlackConfiguration",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/integrations/connections/{connectionId}/slack-configuration",tags:["Integrations"],operationId:"integrations.updateSlackConfiguration",summary:"Update Slack connection configuration",description:"Update Slack connection configuration. Omitted fields are left unchanged."}}},createSlackChannel:{"~orpc":{errorMap:{},meta:{operationId:"integrations.createSlackChannel",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/integrations/slack/channels",tags:["Integrations"],operationId:"integrations.createSlackChannel",summary:"Create a Slack channel",description:"Create a public channel in the organization's connected Slack workspace and invite the calling user. Requires the Slack connection to hold the channels:manage bot scope. The new channel appears as an alert destination once the channel catalog refresh completes.",successStatus:201}}},listSlackChannelProjectMappings:{"~orpc":{errorMap:{},meta:{operationId:"integrations.listSlackChannelProjectMappings",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/integrations/connections/{connectionId}/slack-channel-project-mappings",tags:["Integrations"],operationId:"integrations.listSlackChannelProjectMappings",summary:"List Slack channel-to-project mappings",description:"List channel-to-project mappings for a Slack connection."}}},setSlackChannelProjectMapping:{"~orpc":{errorMap:{},meta:{operationId:"integrations.setSlackChannelProjectMapping",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PUT",path:"/integrations/connections/{connectionId}/slack-channel-project-mappings/{slackChannelId}",tags:["Integrations"],operationId:"integrations.setSlackChannelProjectMapping",summary:"Set a Slack channel-to-project mapping",description:"Create or update the channel-to-project mapping for one Slack channel. Idempotent on (connection, channel)."}}},deleteSlackChannelProjectMapping:{"~orpc":{errorMap:{},meta:{operationId:"integrations.deleteSlackChannelProjectMapping",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/integrations/connections/{connectionId}/slack-channel-project-mappings/{slackChannelId}",tags:["Integrations"],operationId:"integrations.deleteSlackChannelProjectMapping",summary:"Delete a Slack channel-to-project mapping",description:"Delete a channel-to-project mapping."}}}},notificationChannels:{getProject:{"~orpc":{errorMap:{},meta:{operationId:"notificationChannels.getProject",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/notification-channels",tags:["Notification channels"],operationId:"notificationChannels.getProject",summary:"List project notification channels",description:"List a project's notification channels with preferences, prerequisites, connection state, configured destinations, and supported notification types."}}}},notificationDeliveryRules:{list:{"~orpc":{errorMap:{},meta:{operationId:"notificationDeliveryRules.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/notification-delivery-rules",tags:["Notification delivery rules"],operationId:"notificationDeliveryRules.list",summary:"List delivery rules",description:"List the positive delivery rules for a project."}}},options:{"~orpc":{errorMap:{},meta:{operationId:"notificationDeliveryRules.options",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/notification-delivery-rules/options",tags:["Notification delivery rules"],operationId:"notificationDeliveryRules.options",summary:"Get delivery rule options",description:"List available destinations, events, and conditions for project delivery rules."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"notificationDeliveryRules.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/notification-delivery-rules",tags:["Notification delivery rules"],operationId:"notificationDeliveryRules.create",summary:"Create a delivery rule",description:"Create a positive project notification delivery rule."}}},update:{"~orpc":{errorMap:{},meta:{operationId:"notificationDeliveryRules.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PUT",path:"/notification-delivery-rules/{ruleId}",tags:["Notification delivery rules"],operationId:"notificationDeliveryRules.update",summary:"Update a delivery rule",description:"Replace a positive delivery rule atomically."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"notificationDeliveryRules.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/notification-delivery-rules/{ruleId}",tags:["Notification delivery rules"],operationId:"notificationDeliveryRules.delete",summary:"Delete a delivery rule",description:"Delete a positive delivery rule without deleting its reusable destinations."}}}},taskCreationRules:{list:{"~orpc":{errorMap:{},meta:{operationId:"taskCreationRules.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/task-creation-rules",tags:["Task creation rules"],operationId:"taskCreationRules.list",summary:"List task creation rules",description:"List the automatic task creation rules for a project in evaluation priority order."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"taskCreationRules.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/task-creation-rules/{ruleId}",tags:["Task creation rules"],operationId:"taskCreationRules.get",summary:"Get a task creation rule",description:"Get a single task creation rule by ID."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"taskCreationRules.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/task-creation-rules",tags:["Task creation rules"],operationId:"taskCreationRules.create",summary:"Create a task creation rule",description:"Create an automatic task creation rule that files tickets in a connected tracker when issues trigger.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"taskCreationRules.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/task-creation-rules/{ruleId}",tags:["Task creation rules"],operationId:"taskCreationRules.update",summary:"Update a task creation rule",description:"Update an automatic task creation rule."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"taskCreationRules.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/task-creation-rules/{ruleId}",tags:["Task creation rules"],operationId:"taskCreationRules.delete",summary:"Delete a task creation rule",description:"Soft-delete an automatic task creation rule."}}},reorder:{"~orpc":{errorMap:{},meta:{operationId:"taskCreationRules.reorder",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/task-creation-rules/reorder",tags:["Task creation rules"],operationId:"taskCreationRules.reorder",summary:"Reorder task creation rules",description:"Atomically reorder all task creation rules for a project, assigning priorities matching the array order."}}}},mcpConnectors:{listProviders:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.listProviders",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/mcp-connectors/providers",tags:["MCP Connectors"],operationId:"mcpConnectors.listProviders",summary:"List MCP connector providers",description:"List all supported MCP connector providers with their auth mode and setup skill."}}},list:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/mcp-connectors",tags:["MCP Connectors"],operationId:"mcpConnectors.list",summary:"List MCP connectors",description:"List configured MCP connectors within one project with provider, status, and enabled-tool count."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/mcp-connectors/{connectionId}",tags:["MCP Connectors"],operationId:"mcpConnectors.get",summary:"Get an MCP connector",description:"Get one configured MCP connector by connection ID."}}},details:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.details",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/mcp-connectors/{connectionId}/details",tags:["MCP Connectors"],operationId:"mcpConnectors.details",summary:"Inspect an MCP connector's tools",description:"Inspect one MCP connector's tool surface, including each tool's name, description, and read-only status."}}},search:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.search",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/mcp-connectors/tools/search",tags:["MCP Connectors"],operationId:"mcpConnectors.search",summary:"Search MCP connector tools",description:"Search executable third-party MCP connector tools by free-text query. Empty query lists connectors; empty query plus namespace enumerates that connector. Hits omit input schemas unless includeInputSchema is true, which requires one exact namespaced tool and always returns at most one hit."}}},describe:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.describe",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/mcp-connectors/tools/describe",tags:["MCP Connectors"],operationId:"mcpConnectors.describe",summary:"Describe an MCP connector tool",description:"Load one executable third-party MCP connector tool, including its input schema."}}},call:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.call",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/mcp-connectors/tools/call",tags:["MCP Connectors"],operationId:"mcpConnectors.call",summary:"Call an MCP connector tool",description:"Invoke one executable third-party MCP connector tool using that connection's stored credential."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/mcp-connectors",tags:["MCP Connectors"],operationId:"mcpConnectors.create",summary:"Create an MCP connector",description:"Create a preset MCP connector with header-based or AWS SigV4 authentication. The server URL must match the selected provider's supported endpoints. Connects immediately and returns the connector with its discovered tool snapshot.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/mcp-connectors/{connectionId}",tags:["MCP Connectors"],operationId:"mcpConnectors.update",summary:"Update an MCP connector",description:"Replace credentials on an existing preset MCP connector and retry discovery while preserving its identity and tool policy. Supply providerId to reject a connector from a different provider before any credentials are used. Omit credentials to retry discovery with saved credentials. OAuth connectors use the OAuth reconnect operation."}}},disconnect:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.disconnect",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/mcp-connectors/{connectionId}",tags:["MCP Connectors"],operationId:"mcpConnectors.disconnect",summary:"Disconnect an MCP connector",description:"Disconnect and permanently remove an MCP connector.",successStatus:204}}},setReadOnly:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.setReadOnly",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/mcp-connectors/{connectionId}/read-only",tags:["MCP Connectors"],operationId:"mcpConnectors.setReadOnly",summary:"Toggle an MCP connector's read-only mode",description:"Toggle the read-only restriction on an MCP connector."}}},beginOAuthInstall:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.beginOAuthInstall",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/mcp-connectors/oauth/begin",tags:["MCP Connectors"],operationId:"mcpConnectors.beginOAuthInstall",summary:"Begin an MCP connector OAuth install",description:"Begin an OAuth browser flow to install or reconnect a preset MCP connector. Open the authorization URL in the user's browser, then poll getMcpOAuthInstallAttempt with the returned connectionId and requestId to check this attempt's completion.",successStatus:201}}},getOAuthInstallAttempt:{"~orpc":{errorMap:{},meta:{operationId:"mcpConnectors.getOAuthInstallAttempt",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/mcp-connectors/oauth/attempts/{connectionId}",tags:["MCP Connectors"],operationId:"mcpConnectors.getOAuthInstallAttempt",summary:"Get an MCP connector OAuth install attempt",description:"Poll the status of an in-progress OAuth MCP connector install. Returns authorizing while the user completes the browser flow, connected on success, or error on failure."}}}},sandboxEnvironmentVariables:{list:{"~orpc":{errorMap:{},meta:{operationId:"sandboxEnvironmentVariables.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/sandbox-environment-variables",tags:["Sandbox Environment Variables"],operationId:"sandboxEnvironmentVariables.list",summary:"List sandbox environment variables",description:"List configured custom sandbox environment variable keys for a project without exposing secret values."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"sandboxEnvironmentVariables.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/sandbox-environment-variables/{key}",tags:["Sandbox Environment Variables"],operationId:"sandboxEnvironmentVariables.get",summary:"Get sandbox environment variable",description:"Check whether a specific custom sandbox environment variable is configured for a project."}}},upsert:{"~orpc":{errorMap:{},meta:{operationId:"sandboxEnvironmentVariables.upsert",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/sandbox-environment-variables",tags:["Sandbox Environment Variables"],operationId:"sandboxEnvironmentVariables.upsert",summary:"Upsert sandbox environment variables",description:"Set or update custom sandbox environment variables for a project. Merges provided variables with existing ones. Values are encrypted server-side and never returned.",successStatus:200}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"sandboxEnvironmentVariables.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/sandbox-environment-variables/{key}",tags:["Sandbox Environment Variables"],operationId:"sandboxEnvironmentVariables.delete",summary:"Delete sandbox environment variable",description:"Delete a custom sandbox environment variable from a project by key name."}}}},sandboxInitScript:{get:{"~orpc":{errorMap:{},meta:{operationId:"sandboxInitScript.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/sandbox/init-script",tags:["Sandbox Init Script"],operationId:"sandboxInitScript.get",summary:"Get sandbox init script",description:"Fetch the custom sandbox initialization script configured for a project."}}},upsert:{"~orpc":{errorMap:{},meta:{operationId:"sandboxInitScript.upsert",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PUT",path:"/sandbox/init-script",tags:["Sandbox Init Script"],operationId:"sandboxInitScript.upsert",summary:"Upsert sandbox init script",description:"Set or replace the custom sandbox initialization script for a project.",successStatus:200}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"sandboxInitScript.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/sandbox/init-script",tags:["Sandbox Init Script"],operationId:"sandboxInitScript.delete",summary:"Delete sandbox init script",description:"Delete the custom sandbox initialization script from a project."}}}},sandboxClis:{deleteCli:{"~orpc":{errorMap:{},meta:{operationId:"sandboxClis.deleteCli",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/sandbox-clis/config/{cliType}",tags:["Sandbox CLIs"],operationId:"sandboxClis.deleteCli",summary:"Disconnect CLI",description:"Delete a project's stored CLI connection. Integration-managed access remains available until its owning integration is disconnected."}}},listConnections:{"~orpc":{errorMap:{},meta:{operationId:"sandboxClis.listConnections",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/sandbox-clis/connections",tags:["Sandbox CLIs"],operationId:"sandboxClis.listConnections",summary:"List CLI connections",description:"List a project's stored and integration-backed sandbox CLI connections without returning secret values."}}},listTypes:{"~orpc":{errorMap:{},meta:{operationId:"sandboxClis.listTypes",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/sandbox-clis/types",tags:["Sandbox CLIs"],operationId:"sandboxClis.listTypes",summary:"List CLI types",description:"List all supported sandbox CLI types with their environment variable requirements and setup skills."}}},testCli:{"~orpc":{errorMap:{},meta:{operationId:"sandboxClis.testCli",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/sandbox-clis/test",tags:["Sandbox CLIs"],operationId:"sandboxClis.testCli",summary:"Test CLI connection",description:"Validate unsaved CLI credentials in a read-only ephemeral sandbox without persisting them."}}},verify:{"~orpc":{errorMap:{},meta:{operationId:"sandboxClis.verify",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/sandbox-clis/{cliType}/verify",tags:["Sandbox CLIs"],operationId:"sandboxClis.verify",summary:"Check saved CLI credentials",description:"Check the current saved credentials and record authoritative results. Transient failures leave prior evidence unchanged."}}},upsertCli:{"~orpc":{errorMap:{},meta:{operationId:"sandboxClis.upsertCli",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/sandbox-clis/config",tags:["Sandbox CLIs"],operationId:"sandboxClis.upsertCli",summary:"Upsert CLI connection",description:"Set or replace a project's CLI connection credentials (e.g. the kubectl CLI's KUBECONFIG_CONTENTS). Values are encrypted server-side and never returned. Requires write access to the target project.",successStatus:200}}}},scripts:{list:{"~orpc":{errorMap:{},meta:{operationId:"scripts.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/scripts",tags:["Scripts"],operationId:"scripts.list",summary:"List scripts",description:"List durable bash scripts stored for a project."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"scripts.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/scripts/{name}",tags:["Scripts"],operationId:"scripts.get",summary:"Get a script",description:"Get a single project script by name, including its body."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"scripts.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/scripts",tags:["Scripts"],operationId:"scripts.create",summary:"Create a script",description:"Create a durable bash script for a project.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"scripts.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/scripts/{name}",tags:["Scripts"],operationId:"scripts.update",summary:"Update a script",description:"Update a project script's body and/or description."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"scripts.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/scripts/{name}",tags:["Scripts"],operationId:"scripts.delete",summary:"Delete a script",description:"Soft-delete a project script by name.",successStatus:204}}}},signalDefinitions:{list:{"~orpc":{errorMap:{},meta:{operationId:"signalDefinitions.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/signal-definitions",tags:["Signal definitions"],operationId:"signalDefinitions.list",summary:"List signal definitions",description:"List signal definitions in a project."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"signalDefinitions.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/signal-definitions/{signalDefinitionId}",tags:["Signal definitions"],operationId:"signalDefinitions.get",summary:"Get a signal definition",description:"Get a single signal definition by ID."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"signalDefinitions.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/signal-definitions",tags:["Signal definitions"],operationId:"signalDefinitions.create",summary:"Create a signal definition",description:"Create a CEL signal definition for a project.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"signalDefinitions.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/signal-definitions/{signalDefinitionId}",tags:["Signal definitions"],operationId:"signalDefinitions.update",summary:"Update a signal definition",description:"Update a signal definition's name, CEL body, or enabled state."}}},disable:{"~orpc":{errorMap:{},meta:{operationId:"signalDefinitions.disable",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/signal-definitions/{signalDefinitionId}/disable",tags:["Signal definitions"],operationId:"signalDefinitions.disable",summary:"Disable a signal definition",description:"Disable a signal definition so it stops matching logs."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"signalDefinitions.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/signal-definitions/{signalDefinitionId}",tags:["Signal definitions"],operationId:"signalDefinitions.delete",summary:"Delete a signal definition",description:"Permanently delete a signal definition.",successStatus:204}}}},memory:{put:{"~orpc":{errorMap:{},meta:{operationId:"memory.put",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PUT",path:"/memory",tags:["Memory"],operationId:"memory.put",summary:"Create or replace a memory document",description:"Create or replace a curated project memory document. Embeds on success."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"memory.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/memory",tags:["Memory"],operationId:"memory.create",summary:"Create a memory document",description:"Create a curated project memory document at a path that holds no document. Fails with a conflict when the path already exists; never replaces a document. Embeds on success.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"memory.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/memory/document",tags:["Memory"],operationId:"memory.update",summary:"Update a memory document",description:"Replace the body of an existing curated project memory document. Fails with not found when no document exists at the path; never creates one. Embeds on success."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"memory.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/memory/document",tags:["Memory"],operationId:"memory.get",summary:"Get a memory document",description:"Get one project memory document by id or path."}}},list:{"~orpc":{errorMap:{},meta:{operationId:"memory.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/memory",tags:["Memory"],operationId:"memory.list",summary:"List memory documents",description:"List project memory catalog rows without embedding search."}}},search:{"~orpc":{errorMap:{},meta:{operationId:"memory.search",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/memory/search",tags:["Memory"],operationId:"memory.search",summary:"Search project memory",description:"Hybrid semantic and keyword search over project memory documents."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"memory.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/memory/document",tags:["Memory"],operationId:"memory.delete",summary:"Delete a memory document",description:"Soft-delete a curated project memory document by id or path.",successStatus:204}}}},supportTickets:{create:{"~orpc":{errorMap:{},meta:{operationId:"supportTickets.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/support-tickets",tags:["Support Tickets"],operationId:"supportTickets.create",summary:"File a support ticket",description:"File a support ticket or feature request with Sazabi support. The requester is the authenticated person; replies arrive in the dashboard support widget and by email.",successStatus:201}}},availability:{"~orpc":{errorMap:{},meta:{operationId:"supportTickets.availability",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/support-tickets/availability",tags:["Support Tickets"],operationId:"supportTickets.availability",summary:"Check whether support tickets can be filed",description:"Report whether this environment can file support tickets: the support desk is configured and reachable."}}}},onboarding:{continueWithFree:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.continueWithFree",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/onboarding/continue-with-free",tags:["Onboarding"],operationId:"onboarding.continueWithFree",summary:"Continue onboarding with Free",description:"Confirm the organization's existing active Free plan. Requires billing management permission; does not create a subscription or request payment."}}},ensureDefaultProject:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.ensureDefaultProject",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/onboarding/ensure-default-project",tags:["Onboarding"],operationId:"onboarding.ensureDefaultProject",summary:"Ensure the default project",description:"Create the organization's default project unless it already has an active one, and return whichever applies. Atomic per organization, so concurrent onboarding surfaces cannot create duplicates. Requires settings write permission."}}},getState:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.getState",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/onboarding/state",tags:["Onboarding"],operationId:"onboarding.getState",summary:"Get onboarding state",description:"Read onboarding progress for the authenticated user."}}},skipIntegration:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.skipIntegration",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/onboarding/skip-integration",tags:["Onboarding"],operationId:"onboarding.skipIntegration",summary:"Skip an integration step",description:"Skip a GitHub or Slack integration step during onboarding."}}},skipGithubAppInstallation:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.skipGithubAppInstallation",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/onboarding/skip-github-app",tags:["Onboarding"],operationId:"onboarding.skipGithubAppInstallation",summary:"Skip GitHub App installation",description:"Skip GitHub App installation during onboarding."}}},skipSampleIssue:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.skipSampleIssue",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/onboarding/skip-sample-issue",tags:["Onboarding"],operationId:"onboarding.skipSampleIssue",summary:"Skip the test issue",description:"Skip the optional test issue during onboarding."}}},completeSampleIssue:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.completeSampleIssue",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/onboarding/complete-sample-issue",tags:["Onboarding"],operationId:"onboarding.completeSampleIssue",summary:"Complete the test issue step",description:"Mark the sample-issue onboarding step complete after viewing the test issue."}}},finish:{"~orpc":{errorMap:{},meta:{operationId:"onboarding.finish",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/onboarding/finish",tags:["Onboarding"],operationId:"onboarding.finish",summary:"Finish onboarding",description:"Mark onboarding complete when all prerequisites are satisfied."}}}},organizations:{list:{"~orpc":{errorMap:{},meta:{operationId:"organizations.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/organizations",tags:["Organizations"],operationId:"organizations.list",summary:"List organizations",description:"List organizations available to the current credential."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"organizations.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/organizations/{organizationId}",tags:["Organizations"],operationId:"organizations.get",summary:"Get an organization",description:"Get one organization by ID."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"organizations.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/organizations",tags:["Organizations"],operationId:"organizations.create",summary:"Create an organization",description:"Create an organization for the authenticated user.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"organizations.update",backend:"api",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}}}]},route:{method:"PATCH",path:"/organizations/{organizationId}",tags:["Organizations"],operationId:"organizations.update",summary:"Update an organization",description:"Update one organization."}}}},members:{list:{"~orpc":{errorMap:{},meta:{operationId:"members.list",backend:"api",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"}]}}]},route:{method:"GET",path:"/members",tags:["Members"],operationId:"members.list",summary:"List members",description:"List members in an organization."}}},updateRole:{"~orpc":{errorMap:{},meta:{operationId:"members.updateRole",backend:"api",pagination:"none",async:"sync",examples:[{name:"promote-member",input:{organizationId:"organization-123",member:"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"}}}]},route:{method:"PATCH",path:"/members/{member}/role",tags:["Members"],operationId:"members.updateRole",summary:"Update a member's role",description:"Update a member's organization role."}}},remove:{"~orpc":{errorMap:{},meta:{operationId:"members.remove",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/members/{member}",tags:["Members"],operationId:"members.remove",summary:"Remove a member",description:"Remove a member from an organization.",inputStructure:"detailed"}}},invite:{"~orpc":{errorMap:{},meta:{operationId:"members.invite",backend:"api",pagination:"none",async:"sync",examples:[{name:"invite-member",input:{organizationId:"organization-123",email:"newhire@example.com",role:"member"},output:{invitation:{id:"invitation-123",email:"newhire@example.com",role:"member",status:"pending",createdAt:"2026-01-01T00:00:00.000Z",expiresAt:"2026-01-08T00:00:00.000Z"}}}]},route:{method:"POST",path:"/members/invitations",tags:["Members"],operationId:"members.invite",summary:"Invite a member",description:"Invite a person to the organization by email.",successStatus:201}}},listInvitations:{"~orpc":{errorMap:{},meta:{operationId:"members.listInvitations",backend:"api",pagination:"none",async:"sync",examples:[{name:"organization-invitations",input:{organizationId:"organization-123"},output:{invitations:[{id:"invitation-123",email:"newhire@example.com",role:"member",status:"pending",createdAt:"2026-01-01T00:00:00.000Z",expiresAt:"2026-01-08T00:00:00.000Z"}]}}]},route:{method:"GET",path:"/members/invitations",tags:["Members"],operationId:"members.listInvitations",summary:"List invitations",description:"List pending invitations for an organization."}}},revokeInvitation:{"~orpc":{errorMap:{},meta:{operationId:"members.revokeInvitation",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/members/invitations/{invitationId}",tags:["Members"],operationId:"members.revokeInvitation",summary:"Revoke an invitation",description:"Revoke a pending invitation.",inputStructure:"detailed"}}}},teams:{list:{"~orpc":{errorMap:{},meta:{operationId:"teams.list",backend:"api",pagination:"none",async:"sync",examples:[{name:"organization-teams",input:{organizationId:"organization-123"},output:{teams:[{id:"5c0f9866-31ab-4237-94cc-a1d0ba2f6de2",name:"Payments",description:"Owns checkout and billing components.",createdAt:"2026-01-01T00:00:00.000Z",memberCount:4}]}}]},route:{method:"GET",path:"/teams",tags:["Teams"],operationId:"teams.list",summary:"List teams",description:"List teams in an organization."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"teams.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/teams",tags:["Teams"],operationId:"teams.create",summary:"Create a team",description:"Create a team in an organization.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"teams.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/teams/{teamId}",tags:["Teams"],operationId:"teams.update",summary:"Update a team",description:"Rename a team or update its description."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"teams.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/teams/{teamId}",tags:["Teams"],operationId:"teams.delete",summary:"Delete a team",description:"Delete a team, its memberships, and its component-ownership assignments.",inputStructure:"detailed"}}},addMember:{"~orpc":{errorMap:{},meta:{operationId:"teams.addMember",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/teams/{teamId}/members",tags:["Teams"],operationId:"teams.addMember",summary:"Add a team member",description:"Add an active organization member to a team.",successStatus:201}}},removeMember:{"~orpc":{errorMap:{},meta:{operationId:"teams.removeMember",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/teams/{teamId}/members/{userId}",tags:["Teams"],operationId:"teams.removeMember",summary:"Remove a team member",description:"Remove a member from a team.",inputStructure:"detailed"}}},listMembers:{"~orpc":{errorMap:{},meta:{operationId:"teams.listMembers",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/teams/{teamId}/members",tags:["Teams"],operationId:"teams.listMembers",summary:"List team members",description:"List a team's active members."}}}},publicKeys:{list:{"~orpc":{errorMap:{},meta:{operationId:"publicKeys.list",backend:"api",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,deactivatedAt:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}],nextCursor:null}}]},route:{method:"GET",path:"/public-keys",tags:["Public Keys"],operationId:"publicKeys.list",summary:"List public keys",description:"List public keys within one project."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"publicKeys.get",backend:"api",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,deactivatedAt:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}}}]},route:{method:"GET",path:"/public-keys/{keyId}",tags:["Public Keys"],operationId:"publicKeys.get",summary:"Get a public key",description:"Get one public key within one project."}}},ensureLogForwarding:{"~orpc":{errorMap:{},meta:{operationId:"publicKeys.ensureLogForwarding",backend:"api",pagination:"none",async:"sync",examples:[{name:"ensure-log-forwarding-public-key",input:{projectId:"11111111-1111-4111-8111-111111111111"},output:{publicKey:{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",name:"sazabi-cli-forward",dataSourceConnectionId:null,deactivatedAt:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z",value:"sazabi_public_example"}}}]},route:{method:"POST",path:"/public-keys/log-forwarding/ensure",tags:["Public Keys"],operationId:"publicKeys.ensureLogForwarding",summary:"Ensure a log forwarding public key",description:"Ensure a reusable project-scoped public key exists for CLI log forwarding."}}},update:{"~orpc":{errorMap:{},meta:{operationId:"publicKeys.update",backend:"api",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,deactivatedAt:null,expiresAt:null,lastUsedAt:null,createdAt:"2026-01-01T00:00:00.000Z"}}}]},route:{method:"PATCH",path:"/public-keys/{keyId}",tags:["Public Keys"],operationId:"publicKeys.update",summary:"Update a public key",description:"Update one public key within one project."}}},deactivate:{"~orpc":{errorMap:{},meta:{operationId:"publicKeys.deactivate",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/public-keys/{keyId}/deactivate",tags:["Public Keys"],operationId:"publicKeys.deactivate",summary:"Deactivate a public key",description:"Deactivate one public key within one project. Recently validated requests may continue to authenticate for a short period after deactivation.",inputStructure:"detailed"}}}},secretKeys:{list:{"~orpc":{errorMap:{},meta:{operationId:"secretKeys.list",backend:"api",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}}]},route:{method:"GET",path:"/secret-keys",tags:["Secret Keys"],operationId:"secretKeys.list",summary:"List secret keys",description:"List secret keys within the organization."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"secretKeys.get",backend:"api",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"}}}]},route:{method:"GET",path:"/secret-keys/{keyId}",tags:["Secret Keys"],operationId:"secretKeys.get",summary:"Get a secret key",description:"Get one secret key within the organization."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"secretKeys.create",backend:"api",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"}}}]},route:{method:"POST",path:"/secret-keys",tags:["Secret Keys"],operationId:"secretKeys.create",summary:"Create a secret key",description:"Create one secret key within the organization.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"secretKeys.update",backend:"api",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"}}}]},route:{method:"PATCH",path:"/secret-keys/{keyId}",tags:["Secret Keys"],operationId:"secretKeys.update",summary:"Update a secret key",description:"Update one secret key within the organization."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"secretKeys.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/secret-keys/{keyId}",tags:["Secret Keys"],operationId:"secretKeys.delete",summary:"Delete a secret key",description:"Delete one secret key within the organization.",successStatus:204,inputStructure:"detailed"}}}},projects:{list:{"~orpc":{errorMap:{},meta:{operationId:"projects.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/projects",tags:["Projects"],operationId:"projects.list",summary:"List projects",description:"List projects in an organization."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"projects.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/projects/{projectId}",tags:["Projects"],operationId:"projects.get",summary:"Get a project",description:"Get one project by ID."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"projects.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/projects",tags:["Projects"],operationId:"projects.create",summary:"Create a project",description:"Create one project in an organization.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"projects.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PATCH",path:"/projects/{projectId}",tags:["Projects"],operationId:"projects.update",summary:"Update a project",description:"Update (rename) one project by ID. User credentials require the `settings:write` organization permission (admin or owner role)."}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"projects.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/projects/{projectId}",tags:["Projects"],operationId:"projects.delete",summary:"Delete a project",description:"Delete one project by ID. User credentials require the `settings:write` organization permission (admin or owner role).",successStatus:204}}}},search:{threads:{"~orpc":{errorMap:{},meta:{operationId:"search.threads",backend:"api",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}}}]},route:{method:"GET",path:"/search/threads",tags:["Search"],operationId:"search.threads",summary:"Search threads",description:"Search threads within one project."}}},messages:{"~orpc":{errorMap:{},meta:{operationId:"search.messages",backend:"api",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}}}]},route:{method:"GET",path:"/search/messages",tags:["Search"],operationId:"search.messages",summary:"Search messages",description:"Search messages within one project."}}}},messages:{list:{"~orpc":{errorMap:{},meta:{operationId:"messages.list",backend:"api",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?"}],source:"api",createdAt:"2026-01-01T00:00:00.000Z"}],nextCursor:null}}]},route:{method:"GET",path:"/threads/{threadId}/messages",tags:["Messages"],operationId:"messages.list",summary:"List messages in a thread",description:"List messages in a thread with cursor pagination."}}},append:{"~orpc":{errorMap:{},meta:{operationId:"messages.append",backend:"api",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,failureClass:null,failureRetryable:null}}]},route:{method:"POST",path:"/threads/{threadId}/messages",tags:["Messages"],operationId:"messages.append",summary:"Append a message to a thread",description:"Append a user message to an existing thread and trigger a deferred run.",successStatus:201}}}},threads:{list:{"~orpc":{errorMap:{},meta:{operationId:"threads.list",backend:"api",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",source:"api",createdAt:"2026-01-01T00:00:00.000Z",updatedAt:"2026-01-01T00:05:00.000Z"}],nextCursor:null}}]},route:{method:"GET",path:"/threads",tags:["Threads"],operationId:"threads.list",summary:"List threads",description:"List threads in a project, optionally filtered by status."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"threads.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/threads/{threadId}",tags:["Threads"],operationId:"threads.get",summary:"Get a thread",description:"Get a thread and its messages."}}},getStatus:{"~orpc":{errorMap:{},meta:{operationId:"threads.getStatus",backend:"api",pagination:"none",async:"sync",examples:[{name:"processing-thread",input:{threadId:"22222222-2222-4222-8222-222222222222"},output:{status:"processing",lastRunStatus:null}}]},route:{method:"GET",path:"/threads/{threadId}/status",tags:["Threads"],operationId:"threads.getStatus",summary:"Get a thread's status",description:"Get the current processing status for a thread."}}},stop:{"~orpc":{errorMap:{},meta:{operationId:"threads.stop",backend:"api",pagination:"none",async:"sync",examples:[{name:"stop-processing-thread",input:{threadId:"22222222-2222-4222-8222-222222222222"},output:{success:!0}}]},route:{method:"POST",path:"/threads/{threadId}/stop",tags:["Threads"],operationId:"threads.stop",summary:"Stop a thread's run",description:"Stop a thread's in-flight run. Idempotent and best-effort: returns success even when the thread has no active run."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"threads.create",backend:"api",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,failureClass:null,failureRetryable:null}}]},route:{method:"POST",path:"/threads",tags:["Threads"],operationId:"threads.create",summary:"Create a thread",description:"Create a thread with an initial message and optionally wait for the agent response.",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"threads.update",backend:"api",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",source:"api",createdAt:"2026-01-01T00:00:00.000Z",updatedAt:"2026-01-01T00:10:00.000Z"}}}]},route:{method:"PATCH",path:"/threads/{threadId}",tags:["Threads"],operationId:"threads.update",summary:"Update a thread",description:"Update a thread's status."}}},fork:{"~orpc":{errorMap:{},meta:{operationId:"threads.fork",backend:"api",pagination:"none",async:"sync",examples:[{name:"fork-from-message",input:{threadId:"22222222-2222-4222-8222-222222222222",messageId:"44444444-4444-4444-8444-444444444444"},output:{thread:{id:"66666666-6666-4666-8666-666666666666",projectId:"11111111-1111-4111-8111-111111111111",title:"API returning 500s (fork)",status:"regular",source:"api",createdAt:"2026-01-01T00:20:00.000Z",updatedAt:"2026-01-01T00:20:00.000Z"}}}]},route:{method:"POST",path:"/threads/{threadId}/fork",tags:["Threads"],operationId:"threads.fork",summary:"Fork a thread",description:"Fork a thread from a specific message, creating a new thread that copies messages up to that point.",successStatus:201}}},setVisibility:{"~orpc":{errorMap:{},meta:{operationId:"threads.setVisibility",backend:"api",pagination:"none",async:"sync",examples:[{name:"make-private",input:{threadId:"22222222-2222-4222-8222-222222222222",visibility:"private"},output:{thread:{id:"22222222-2222-4222-8222-222222222222",projectId:"11111111-1111-4111-8111-111111111111",title:"API returning 500s",status:"regular",source:"api",createdAt:"2026-01-01T00:00:00.000Z",updatedAt:"2026-01-01T00:30:00.000Z"},visibility:"private"}}]},route:{method:"PATCH",path:"/threads/{threadId}/visibility",tags:["Threads"],operationId:"threads.setVisibility",summary:"Set a thread's visibility",description:"Set a thread's visibility to private or organization."}}},createShareLink:{"~orpc":{errorMap:{},meta:{operationId:"threads.createShareLink",backend:"api",pagination:"none",async:"sync",examples:[{name:"create-share-link",input:{threadId:"22222222-2222-4222-8222-222222222222"},output:{share:{shareId:"55555555-5555-4555-8555-555555555555",threadId:"22222222-2222-4222-8222-222222222222",url:"https://app.sazabi.com/share/55555555-5555-4555-8555-555555555555",createdAt:"2026-01-01T00:40:00.000Z"}}}]},route:{method:"POST",path:"/threads/{threadId}/share",tags:["Threads"],operationId:"threads.createShareLink",summary:"Create a thread share link",description:"Create a public read-only share link for a thread's current messages.",successStatus:201}}},listShareLinks:{"~orpc":{errorMap:{},meta:{operationId:"threads.listShareLinks",backend:"api",pagination:"none",async:"sync",examples:[{name:"list-share-links",input:{threadId:"22222222-2222-4222-8222-222222222222"},output:{shares:[{shareId:"55555555-5555-4555-8555-555555555555",threadId:"22222222-2222-4222-8222-222222222222",url:"https://app.sazabi.com/share/55555555-5555-4555-8555-555555555555",createdAt:"2026-01-01T00:40:00.000Z"}]}}]},route:{method:"GET",path:"/threads/{threadId}/share",tags:["Threads"],operationId:"threads.listShareLinks",summary:"List thread share links",description:"List active public share links for a thread."}}},revokeShareLink:{"~orpc":{errorMap:{},meta:{operationId:"threads.revokeShareLink",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/threads/{threadId}/share/{shareId}",tags:["Threads"],operationId:"threads.revokeShareLink",summary:"Revoke a thread share link",description:"Revoke a public share link for a thread.",successStatus:204}}}},runs:{list:{"~orpc":{errorMap:{},meta:{operationId:"runs.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/runs",tags:["Runs"],operationId:"runs.list",summary:"List runs",description:"List deferred runs within one project."}}},listForThread:{"~orpc":{errorMap:{},meta:{operationId:"runs.listForThread",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/threads/{threadId}/runs",tags:["Runs"],operationId:"runs.listForThread",summary:"List runs for a thread",description:"List deferred runs for one thread."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"runs.get",backend:"api",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,failureClass:null,failureRetryable:null}},{name:"failed-retryable-run",input:{runId:"44444444-4444-4444-8444-444444444444"},output:{completed:!0,threadId:"22222222-2222-4222-8222-222222222222",runId:"44444444-4444-4444-8444-444444444444",status:"error",response:null,failureClass:"provider",failureRetryable:!0}}]},route:{method:"GET",path:"/runs/{runId}",tags:["Runs"],operationId:"runs.get",summary:"Get a run",description:"Get the current result for a deferred run by run ID."}}},cancel:{"~orpc":{errorMap:{},meta:{operationId:"runs.cancel",backend:"api",pagination:"none",async:"sync",examples:[{name:"cancel-processing-run",input:{runId:"33333333-3333-4333-8333-333333333333"},output:{success:!0}}]},route:{method:"POST",path:"/runs/{runId}/cancel",tags:["Runs"],operationId:"runs.cancel",summary:"Cancel a run",description:"Request cancellation of an in-flight run. Idempotent and best-effort: returns success even when the run has already reached a terminal status."}}}},pullRequests:{list:{"~orpc":{errorMap:{},meta:{operationId:"pullRequests.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/pull-requests",tags:["Pull Requests"],operationId:"pullRequests.list",summary:"List pull requests",description:"List pull requests that Sazabi opened, optionally filtered by status, repository, and requesting user."}}}},issues:{create:{"~orpc":{errorMap:{},meta:{operationId:"issues.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues",tags:["Issues"],operationId:"issues.create",summary:"Create an issue",description:"Create an issue in a project. When root-cause deduplication finds a match, no issue is created: the existing open issue is returned with `created: false` and records the report as a recurrence.",successStatus:201}}},list:{"~orpc":{errorMap:{},meta:{operationId:"issues.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/issues",tags:["Issues"],operationId:"issues.list",summary:"List issues",description:"List issues in a project, optionally filtered by status and severity."}}},search:{"~orpc":{errorMap:{},meta:{operationId:"issues.search",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/issues/search",tags:["Issues"],operationId:"issues.search",summary:"Search issues",description:"Search issues in a project by ranked text over name and description, status, and severity."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"issues.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/issues/{issueId}",tags:["Issues"],operationId:"issues.get",summary:"Get an issue",description:"Get a single issue by ID."}}},getRejectionContext:{"~orpc":{errorMap:{},meta:{operationId:"issues.getRejectionContext",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/issues/{issueId}/rejection",tags:["Issues"],operationId:"issues.getRejectionContext",summary:"Get issue rejection eligibility",description:"Get the rejection deadline, cycle quota, and billing effect for an issue."}}},reject:{"~orpc":{errorMap:{},meta:{operationId:"issues.reject",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues/{issueId}/reject",tags:["Issues"],operationId:"issues.reject",summary:"Reject an issue",description:"Permanently reject an eligible issue and correct one issue usage unit."}}},resolve:{"~orpc":{errorMap:{},meta:{operationId:"issues.resolve",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues/{issueId}/resolve",tags:["Issues"],operationId:"issues.resolve",summary:"Resolve an issue",description:"Resolve an open issue."}}},ignore:{"~orpc":{errorMap:{},meta:{operationId:"issues.ignore",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues/{issueId}/ignore",tags:["Issues"],operationId:"issues.ignore",summary:"Ignore an issue",description:"Ignore an open issue."}}},reopen:{"~orpc":{errorMap:{},meta:{operationId:"issues.reopen",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues/{issueId}/reopen",tags:["Issues"],operationId:"issues.reopen",summary:"Reopen an issue",description:"Reopen a resolved or ignored issue."}}},reassignAndReopen:{"~orpc":{errorMap:{},meta:{operationId:"issues.reassignAndReopen",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues/{issueId}/reassign-and-reopen",tags:["Issues"],operationId:"issues.reassignAndReopen",summary:"Reassign and reopen an issue",description:"Atomically reassign a resolved or ignored issue to an active component and reopen it."}}},mute:{"~orpc":{errorMap:{},meta:{operationId:"issues.mute",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues/{issueId}/mute",tags:["Issues"],operationId:"issues.mute",summary:"Mute an issue",description:"Mute an issue, suppressing future re-fires without changing status."}}},unmute:{"~orpc":{errorMap:{},meta:{operationId:"issues.unmute",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/issues/{issueId}/unmute",tags:["Issues"],operationId:"issues.unmute",summary:"Unmute an issue",description:"Unmute an issue, preserving its current status."}}}},workItems:{create:{"~orpc":{errorMap:{},meta:{operationId:"work-items.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/work-items",tags:["Work Items"],operationId:"work-items.create",summary:"Create a work item (deprecated)",description:"Deprecated alias for `POST /tasks` (create a task); removed in v2.0 (2027-03-01). Create a work item (e.g. a Linear issue) in a connected issue tracker, attributing the write to the requesting user.",successStatus:201,deprecated:!0}}},comment:{"~orpc":{errorMap:{},meta:{operationId:"work-items.comment",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/work-items/{itemId}/comment",tags:["Work Items"],operationId:"work-items.comment",summary:"Comment on a work item (deprecated)",description:"Deprecated alias for `POST /tasks/{taskId}/comment` (comment on a task); removed in v2.0 (2027-03-01). Add a comment to an existing work item.",deprecated:!0}}},transition:{"~orpc":{errorMap:{},meta:{operationId:"work-items.transition",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/work-items/{itemId}/transition",tags:["Work Items"],operationId:"work-items.transition",summary:"Transition a work item (deprecated)",description:"Deprecated alias for `POST /tasks/{taskId}/transition` (transition a task); removed in v2.0 (2027-03-01). Move a work item to a target workflow state.",deprecated:!0}}}},webhooks:{list:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/webhooks",tags:["Webhooks"],operationId:"webhooks.list",summary:"List webhook endpoints",description:"List webhook endpoints in the organization"}}},get:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/webhooks/{webhookId}",tags:["Webhooks"],operationId:"webhooks.get",summary:"Get a webhook endpoint",description:"Get a webhook endpoint and its subscriptions"}}},create:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/webhooks",tags:["Webhooks"],operationId:"webhooks.create",summary:"Create a webhook endpoint",description:"Create an endpoint and return its signing secret once",successStatus:201}}},update:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.update",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PUT",path:"/webhooks/{webhookId}",tags:["Webhooks"],operationId:"webhooks.update",summary:"Update a webhook endpoint",description:"Update endpoint metadata, URL, or static authentication header"}}},delete:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.delete",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/webhooks/{webhookId}",tags:["Webhooks"],operationId:"webhooks.delete",summary:"Delete a webhook endpoint",description:"Tombstone an endpoint, its destinations, and its rules",successStatus:204}}},rotateSecret:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.rotateSecret",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/webhooks/{webhookId}/rotate-secret",tags:["Webhooks"],operationId:"webhooks.rotateSecret",summary:"Rotate a webhook signing secret",description:"Rotate and return the signing secret once"}}},enable:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.enable",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/webhooks/{webhookId}/enable",tags:["Webhooks"],operationId:"webhooks.enable",summary:"Enable a webhook endpoint",description:"Re-enable an endpoint disabled after delivery failures"}}},test:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.test",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/webhooks/{webhookId}/test",tags:["Webhooks"],operationId:"webhooks.test",summary:"Send a test webhook delivery",description:"Send a signed test envelope to an endpoint"}}},subscribe:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.subscribe",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/webhooks/{webhookId}/subscriptions",tags:["Webhooks"],operationId:"webhooks.subscribe",summary:"Subscribe a webhook",description:"Create a project notification rule for a webhook",successStatus:201}}},unsubscribe:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.unsubscribe",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/webhooks/{webhookId}/subscriptions/{subscriptionId}",tags:["Webhooks"],operationId:"webhooks.unsubscribe",summary:"Unsubscribe a webhook",description:"Remove a project notification rule for a webhook",successStatus:204}}},listDeliveries:{"~orpc":{errorMap:{},meta:{operationId:"webhooks.listDeliveries",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/webhooks/{webhookId}/deliveries",tags:["Webhooks"],operationId:"webhooks.listDeliveries",summary:"List webhook deliveries",description:"List delivery history for an endpoint"}}}},billing:{getSummary:{"~orpc":{errorMap:{},meta:{operationId:"billing.getSummary",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/summary",tags:["Billing"],operationId:"billing.getSummary",summary:"Get billing summary",description:"Get a billing summary for the current organization, including plan, balance, and cycle information."}}},getUsage:{"~orpc":{errorMap:{},meta:{operationId:"billing.getUsage",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/usage",tags:["Billing"],operationId:"billing.getUsage",summary:"Get billing usage",description:"Get per-dimension usage breakdown for the current or previous billing cycle."}}},getAccruedUsageCharges:{"~orpc":{errorMap:{},meta:{operationId:"billing.getAccruedUsageCharges",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/usage-charges/accrued",tags:["Billing"],operationId:"billing.getAccruedUsageCharges",summary:"Get accrued usage charges",description:"Get usage charges accrued so far in the open billing cycle, priced under the cycle's plan terms. These settle on the cycle-end usage invoice."}}},listUsageInvoices:{"~orpc":{errorMap:{},meta:{operationId:"billing.listUsageInvoices",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/usage-invoices",tags:["Billing"],operationId:"billing.listUsageInvoices",summary:"List usage invoices",description:"List cycle-end usage invoices — the local settlement record, one per settled billing cycle, zero-total settlements included."}}},listTransactions:{"~orpc":{errorMap:{},meta:{operationId:"billing.listTransactions",backend:"api",pagination:"page",async:"sync",examples:[]},route:{method:"GET",path:"/billing/transactions",tags:["Billing"],operationId:"billing.listTransactions",summary:"List billing transactions",description:"List recent credit ledger transactions with pagination."}}},getAutoTopUp:{"~orpc":{errorMap:{},meta:{operationId:"billing.getAutoTopUp",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/auto-top-up",tags:["Billing"],operationId:"billing.getAutoTopUp",summary:"Get auto top-up settings",description:"Get the organization's credit auto top-up settings (trigger balance, top-up amount, cycle spending limit)."}}},updateAutoTopUp:{"~orpc":{errorMap:{},meta:{operationId:"billing.updateAutoTopUp",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PUT",path:"/billing/auto-top-up",tags:["Billing"],operationId:"billing.updateAutoTopUp",summary:"Update auto top-up settings",description:"Enable/disable and configure credit auto top-up. Requires a user credential with `billing:manage`."}}},purchaseCredits:{"~orpc":{errorMap:{},meta:{operationId:"billing.purchaseCredits",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/credits/purchase",tags:["Billing"],operationId:"billing.purchaseCredits",summary:"Purchase credits",description:"Purchase a one-time amount of credits against the saved payment method. Requires a user credential with `billing:manage` and a stable idempotency key."}}},listPlans:{"~orpc":{errorMap:{},meta:{operationId:"billing.listPlans",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/plans",tags:["Billing"],operationId:"billing.listPlans",summary:"List plans",description:"List the self-serve credit plans available for checkout, including the current plan."}}},previewPlanChange:{"~orpc":{errorMap:{},meta:{operationId:"billing.previewPlanChange",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/plan-change/preview",tags:["Billing"],operationId:"billing.previewPlanChange",summary:"Preview a plan change",description:"Preview the cost and effect of changing to a plan without applying it. Requires a user credential with `billing:manage`."}}},previewSubscriptionCancellation:{"~orpc":{errorMap:{},meta:{operationId:"billing.previewSubscriptionCancellation",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/subscription-cancellation/preview",tags:["Billing"],operationId:"billing.previewSubscriptionCancellation",summary:"Preview subscription cancellation",description:"Preview period-end subscription cancellation without changing billing state."}}},scheduleSubscriptionCancellation:{"~orpc":{errorMap:{},meta:{operationId:"billing.scheduleSubscriptionCancellation",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/subscription-cancellation",tags:["Billing"],operationId:"billing.scheduleSubscriptionCancellation",summary:"Schedule subscription cancellation",description:"Schedule cancellation at the end of the paid billing cycle."}}},resumeSubscriptionCancellation:{"~orpc":{errorMap:{},meta:{operationId:"billing.resumeSubscriptionCancellation",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/subscription-cancellation/resume",tags:["Billing"],operationId:"billing.resumeSubscriptionCancellation",summary:"Resume subscription renewal",description:"Resume renewal before a scheduled cancellation takes effect."}}},changePlan:{"~orpc":{errorMap:{},meta:{operationId:"billing.changePlan",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/plan-change",tags:["Billing"],operationId:"billing.changePlan",summary:"Change the plan",description:"Apply a plan upgrade or schedule a downgrade. Requires a user credential with `billing:manage`."}}},createCheckoutSession:{"~orpc":{errorMap:{},meta:{operationId:"billing.createCheckoutSession",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/checkout-session",tags:["Billing"],operationId:"billing.createCheckoutSession",summary:"Create a checkout session",description:"Create a hosted Stripe Checkout session for first-time subscribe from the terminal. Requires a user credential with `billing:manage`."}}},getCheckoutSessionStatus:{"~orpc":{errorMap:{},meta:{operationId:"billing.getCheckoutSessionStatus",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/checkout-session/{sessionId}",tags:["Billing"],operationId:"billing.getCheckoutSessionStatus",summary:"Get checkout session status",description:"Poll the completion status of a checkout session created by this organization."}}},createPortalSession:{"~orpc":{errorMap:{},meta:{operationId:"billing.createPortalSession",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/billing/portal-session",tags:["Billing"],operationId:"billing.createPortalSession",summary:"Create a billing portal session",description:"Create a Stripe Customer Portal session for updating the payment method. Requires a user credential with `billing:manage`."}}},getPaymentMethod:{"~orpc":{errorMap:{},meta:{operationId:"billing.getPaymentMethod",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/billing/payment-method",tags:["Billing"],operationId:"billing.getPaymentMethod",summary:"Get the payment method",description:"Get a summary of the organization's saved payment method (brand and last 4 digits)."}}}},tasks:{list:{"~orpc":{errorMap:{},meta:{operationId:"tasks.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/tasks",tags:["Onboarding Tasks"],operationId:"tasks.list",summary:"List onboarding tasks",description:"List all onboarding and setup tasks for a project, including their current completion status and a description of what is required to complete each task."}}},skip:{"~orpc":{errorMap:{},meta:{operationId:"tasks.skip",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/tasks/{taskId}/skip",tags:["Onboarding Tasks"],operationId:"tasks.skip",summary:"Skip an onboarding task",description:"Record an organization-wide skip for an optional onboarding task. The skip is shared across surfaces and teammates; completing the task through any door still outranks a recorded skip. Idempotent — re-skipping keeps the original skip record."}}},unskip:{"~orpc":{errorMap:{},meta:{operationId:"tasks.unskip",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/tasks/{taskId}/unskip",tags:["Onboarding Tasks"],operationId:"tasks.unskip",summary:"Reopen a skipped onboarding task",description:"Remove the organization-wide skip record for an onboarding task, reopening it in every onboarding walk. Idempotent — unskipping a task that is not skipped is a no-op."}}},create:{"~orpc":{errorMap:{},meta:{operationId:"tasks.create",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/tasks",tags:["Tasks"],operationId:"tasks.create",summary:"Create a task",description:"Create a task (e.g. a Linear issue) in a connected external tracker, attributing the write to the requesting user.",successStatus:201}}},comment:{"~orpc":{errorMap:{},meta:{operationId:"tasks.comment",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/tasks/{taskId}/comment",tags:["Tasks"],operationId:"tasks.comment",summary:"Comment on a task",description:"Add a comment to an existing task."}}},transition:{"~orpc":{errorMap:{},meta:{operationId:"tasks.transition",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/tasks/{taskId}/transition",tags:["Tasks"],operationId:"tasks.transition",summary:"Transition a task",description:"Move a task to a target workflow state."}}}},recommendations:{list:{"~orpc":{errorMap:{},meta:{operationId:"recommendations.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/recommendations",tags:["Recommendations"],operationId:"recommendations.list",summary:"List recommendations",description:"List a project's configuration recommendations (data sources, MCP connectors, sandbox CLIs, and integrations) with each item's live connection status."}}}},repos:{list:{"~orpc":{errorMap:{},meta:{operationId:"repos.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/repos",tags:["Repos"],operationId:"repos.list",summary:"List repositories",description:"List the repositories available to a project — every repository reachable through the organization's GitHub App installations, the caller's personal forge connections, and integrations — with each one's linked status."}}},add:{"~orpc":{errorMap:{},meta:{operationId:"repos.add",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/repos",tags:["Repos"],operationId:"repos.add",summary:"Link repositories to a project",description:"Link repositories to a project by access source id. Select only one access source per repository; re-linking an already-linked repository refreshes its selected access source."}}},remove:{"~orpc":{errorMap:{},meta:{operationId:"repos.remove",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"DELETE",path:"/repos/{id}",tags:["Repos"],operationId:"repos.remove",summary:"Unlink a repository from a project",description:"Unlink a repository from a project by repository row id.",successStatus:204}}}},components:{list:{"~orpc":{errorMap:{},meta:{operationId:"components.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/components",tags:["Components"],operationId:"components.list",summary:"List components",description:"List status page components in a project."}}},get:{"~orpc":{errorMap:{},meta:{operationId:"components.get",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/components/{componentId}",tags:["Components"],operationId:"components.get",summary:"Get a component",description:"Get a single component by ID."}}},register:{"~orpc":{errorMap:{},meta:{operationId:"components.register",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components",tags:["Components"],operationId:"components.register",summary:"Register a component",description:"Register a status page component in a project, or refresh an existing active component with the same name."}}},deregister:{"~orpc":{errorMap:{},meta:{operationId:"components.deregister",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/{componentId}/deregister",tags:["Components"],operationId:"components.deregister",summary:"Deregister a component",description:"Withdraw this credential's component observation, or — for a human caller — preview the deregistration and confirm it by resubmitting with the previewed componentRevisions."}}},rename:{"~orpc":{errorMap:{},meta:{operationId:"components.rename",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/{componentId}/rename",tags:["Components"],operationId:"components.rename",summary:"Rename a component",description:"Rename an active component while reserving its previous exact name as an alias."}}},assignTeam:{"~orpc":{errorMap:{},meta:{operationId:"components.assignTeam",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"PUT",path:"/components/{componentId}/team",tags:["Components"],operationId:"components.assignTeam",summary:"Assign a component to a team",description:"Assign a component to an owning team, reassign it, or unassign it. A component is owned by at most one team."}}},reactivationPreview:{"~orpc":{errorMap:{},meta:{operationId:"components.reactivationPreview",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/{componentId}/reactivation/preview",tags:["Components"],operationId:"components.reactivationPreview",summary:"Preview a component reactivation",description:"Preview unchanged deregistration-owned dependents that remain eligible for explicit reactivation."}}},reactivate:{"~orpc":{errorMap:{},meta:{operationId:"components.reactivate",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/{componentId}/reactivate",tags:["Components"],operationId:"components.reactivate",summary:"Reactivate a component",description:"Reactivate an inactive canonical component and only the explicitly selected eligible dependents. Prior rules, automations, and relationships stay detached unless explicitly selected."}}},mergePreview:{"~orpc":{errorMap:{},meta:{operationId:"components.mergePreview",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/merge/preview",tags:["Components"],operationId:"components.mergePreview",summary:"Preview a component merge",description:"Preview one-hop redirects, historical preservation, operational rebinding, topology contraction, and policy dispositions for component consolidation."}}},merge:{"~orpc":{errorMap:{},meta:{operationId:"components.merge",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/merge",tags:["Components"],operationId:"components.merge",summary:"Merge a component",description:"Consolidate a source into an active terminal target without rewriting historical issue or observation attribution."}}},relationships:{list:{"~orpc":{errorMap:{},meta:{operationId:"components.relationships.list",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/components/relationships",tags:["Components"],operationId:"components.relationships.list",summary:"List component relationships",description:"List active or historical component topology edges."}}},preview:{"~orpc":{errorMap:{},meta:{operationId:"components.relationships.preview",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/relationships/preview",tags:["Components"],operationId:"components.relationships.preview",summary:"Preview a component relationship change",description:"Preview descendant-scoped notification and automation impact for a topology change."}}},add:{"~orpc":{errorMap:{},meta:{operationId:"components.relationships.add",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/relationships",tags:["Components"],operationId:"components.relationships.add",summary:"Add a component relationship",description:"Add a confirmed, tenant-safe component topology edge."}}},remove:{"~orpc":{errorMap:{},meta:{operationId:"components.relationships.remove",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"POST",path:"/components/relationships/remove",tags:["Components"],operationId:"components.relationships.remove",summary:"Remove a component relationship",description:"Historically end a confirmed component topology edge."}}}},incidents:{list:{"~orpc":{errorMap:{},meta:{operationId:"components.incidents.list",backend:"api",pagination:"cursor",async:"sync",examples:[]},route:{method:"GET",path:"/status-incidents",tags:["Components"],operationId:"components.incidents.list",summary:"List status-page issues",description:"List status-page issues in a project."}}}},timeline:{"~orpc":{errorMap:{},meta:{operationId:"components.timeline",backend:"api",pagination:"none",async:"sync",examples:[]},route:{method:"GET",path:"/components/{componentId}/timeline",tags:["Components"],operationId:"components.timeline",summary:"Get a component status timeline",description:"Get the dense status timeline and incidents for a component over a time window."}}}}}});var xb="https://api.sazabi.com",cx="https://api.platform.sazabi.com",lx="sazabi-cli",F0="urn:ietf:params:oauth:grant-type:device_code",ux=(e)=>{let t=qd(new op(ix,{url:B0(e.apiBaseUrl??xb),headers:async()=>{let s=new Headers({authorization:`Bearer ${await e.credentialProvider.getToken()}`});if(e.clientSource)s.set("x-sazabi-client-source",e.clientSource);if(e.clientVersion)s.set("x-sazabi-client-version",e.clientVersion);if(e.sandboxActorDescriptor)s.set("x-sazabi-sandbox-actor",e.sandboxActorDescriptor);return s},fetch:e.fetch,customErrorResponseBodyDecoder:(s,c)=>{let l=H0(s);if(!l)return null;return new Ye(l.code,{message:l.message,status:c.status,data:{...l.details,operationId:l.operationId,missingContext:l.missingContext,...l.reason!==void 0?{reason:l.reason}:{},...l.entitlementId!==void 0?{entitlementId:l.entitlementId}:{},...l.planSlug!==void 0?{planSlug:l.planSlug}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.current!==void 0?{current:l.current}:{},...l.actionPath!==void 0?{actionPath:l.actionPath}:{},...l.retryAfterSeconds!==void 0?{retryAfterSeconds:l.retryAfterSeconds}:{},...l.issues!==void 0?{issues:l.issues}:{},...l.diagnostics!==void 0?{diagnostics:l.diagnostics}:{},...l.currentRevision!==void 0?{currentRevision:l.currentRevision}:{}}})}})),n=QO({raw:t,credentialProvider:e.credentialProvider,fetch:e.fetch,apiBaseUrl:e.apiBaseUrl??xb,intakeBaseUrl:e.intakeBaseUrl,tailBaseUrl:e.tailBaseUrl}),r=KO({credentialProvider:e.credentialProvider,fetch:e.fetch,apiBaseUrl:e.apiBaseUrl??xb,clientSource:e.clientSource,clientVersion:e.clientVersion}),o=async(s,c)=>t.tasks.create(await Q(e.credentialProvider,s,c)),i=async(s,c)=>t.tasks.comment(await Q(e.credentialProvider,s,c)),a=async(s,c)=>t.tasks.transition(await Q(e.credentialProvider,s,c));return{raw:t,me:async()=>t.me({}),artifacts:{list:async(s={})=>t.artifacts.list(await U(e.credentialProvider,s)),listIssueArtifacts:async(s)=>t.artifacts.listIssueArtifacts(s),get:async(s)=>t.artifacts.get(await U(e.credentialProvider,s)),download:async(s)=>t.artifacts.download(await U(e.credentialProvider,s)),delete:async(s)=>t.artifacts.delete(await U(e.credentialProvider,s))},automations:{list:async(s={})=>t.automations.list(await U(e.credentialProvider,s)),get:async(s)=>t.automations.get(await U(e.credentialProvider,s)),create:async(s)=>t.automations.create(await U(e.credentialProvider,s)),update:async(s)=>t.automations.update(await U(e.credentialProvider,s)),enable:async(s)=>t.automations.enable(await U(e.credentialProvider,s)),disable:async(s)=>t.automations.disable(await U(e.credentialProvider,s)),delete:async(s)=>t.automations.delete(await U(e.credentialProvider,s)),runs:{list:async(s)=>t.automations.runs.list(await U(e.credentialProvider,s)),get:async(s)=>t.automations.runs.get(await U(e.credentialProvider,s)),logs:async(s)=>t.automations.runs.logs(await U(e.credentialProvider,s))}},automationTemplates:{list:()=>t.automationTemplates.list({})},dashboards:{list:async(s={})=>t.dashboards.list(await Un(e.credentialProvider,s,"dashboards.list")),get:async(s)=>t.dashboards.get(await Un(e.credentialProvider,s,"dashboards.get")),validate:async(s)=>t.dashboards.validate(await Un(e.credentialProvider,s,"dashboards.validate")),create:async(s)=>t.dashboards.create(await Un(e.credentialProvider,s,"dashboards.create")),update:async(s)=>t.dashboards.update(await Un(e.credentialProvider,s,"dashboards.update")),render:async(s)=>t.dashboards.render(await Un(e.credentialProvider,s,"dashboards.render")),delete:async(s)=>t.dashboards.delete(await Un(e.credentialProvider,s,"dashboards.delete"))},logs:{...n,ask:async(s)=>t.logs.ask(await U(e.credentialProvider,s)),executeQuery:async(s)=>t.logs.executeQuery(await Un(e.credentialProvider,s,"logs.executeQuery"))},onboarding:{getState:async(s={})=>t.onboarding.getState(await lo(e.credentialProvider,await U(e.credentialProvider,s))),skipSampleIssue:async(s)=>t.onboarding.skipSampleIssue(await lo(e.credentialProvider,s??{})),skipIntegration:async(s)=>t.onboarding.skipIntegration(await ax(e.credentialProvider,s)),skipGithubAppInstallation:async(s)=>t.onboarding.skipGithubAppInstallation(await ax(e.credentialProvider,s??{})),continueWithFree:async(s)=>t.onboarding.continueWithFree(await lo(e.credentialProvider,s??{})),ensureDefaultProject:async(s)=>t.onboarding.ensureDefaultProject(await lo(e.credentialProvider,s??{})),completeSampleIssue:async(s)=>t.onboarding.completeSampleIssue(await lo(e.credentialProvider,s??{})),finish:async(s)=>t.onboarding.finish(s)},organizations:{list:async()=>t.organizations.list({}),get:async(s)=>t.organizations.get(s),create:async(s)=>t.organizations.create(s),update:async(s)=>t.organizations.update(await Q(e.credentialProvider,s,"organizations.update"))},members:{list:async(s={})=>t.members.list(await Q(e.credentialProvider,s,"members.list")),updateRole:async(s)=>t.members.updateRole(await Q(e.credentialProvider,s,"members.updateRole")),remove:async(s)=>{let c=await Q(e.credentialProvider,s,"members.remove");return t.members.remove({params:{member:c.member},query:{organizationId:c.organizationId}})},invite:async(s)=>t.members.invite(await Q(e.credentialProvider,s,"members.invite")),listInvitations:async(s={})=>t.members.listInvitations(await Q(e.credentialProvider,s,"members.listInvitations")),revokeInvitation:async(s)=>{let c=await Q(e.credentialProvider,s,"members.revokeInvitation");return t.members.revokeInvitation({params:{invitationId:c.invitationId},query:{organizationId:c.organizationId}})}},teams:{list:async(s={})=>t.teams.list(await Q(e.credentialProvider,s,"teams.list")),create:async(s)=>t.teams.create(await Q(e.credentialProvider,s,"teams.create")),update:async(s)=>t.teams.update(await Q(e.credentialProvider,s,"teams.update")),delete:async(s)=>{let c=await Q(e.credentialProvider,s,"teams.delete");return t.teams.delete({params:{teamId:c.teamId},query:{organizationId:c.organizationId}})},addMember:async(s)=>t.teams.addMember(await Q(e.credentialProvider,s,"teams.addMember")),removeMember:async(s)=>{let c=await Q(e.credentialProvider,s,"teams.removeMember");return t.teams.removeMember({params:{teamId:c.teamId,userId:c.userId},query:{organizationId:c.organizationId}})},listMembers:async(s)=>t.teams.listMembers(await Q(e.credentialProvider,s,"teams.listMembers"))},publicKeys:{list:async(s={})=>t.publicKeys.list(await U(e.credentialProvider,s)),get:async(s)=>t.publicKeys.get(await U(e.credentialProvider,s)),ensureLogForwarding:async(s={})=>t.publicKeys.ensureLogForwarding(await U(e.credentialProvider,s)),update:async(s)=>t.publicKeys.update(await U(e.credentialProvider,s)),deactivate:async(s)=>{let c=await U(e.credentialProvider,s);return t.publicKeys.deactivate({params:{keyId:c.keyId},query:{projectId:c.projectId}})}},secretKeys:{list:async(s={})=>t.secretKeys.list(await Q(e.credentialProvider,s,"secretKeys.list")),get:async(s)=>t.secretKeys.get(await Q(e.credentialProvider,s,"secretKeys.get")),create:async(s)=>t.secretKeys.create(await Q(e.credentialProvider,s,"secretKeys.create")),update:async(s)=>t.secretKeys.update(await Q(e.credentialProvider,s,"secretKeys.update")),delete:async(s)=>{let{organizationId:c}=await Q(e.credentialProvider,s,"secretKeys.delete");await t.secretKeys.delete({params:{keyId:s.keyId},query:{organizationId:c}})}},search:{threads:async(s)=>t.search.threads(await U(e.credentialProvider,s)),messages:async(s)=>t.search.messages(await U(e.credentialProvider,s))},projects:{list:async(s={})=>t.projects.list(await G0(e.credentialProvider,s)),get:async(s)=>t.projects.get(s),create:async(s)=>t.projects.create(await Q(e.credentialProvider,s,"projects.create")),update:async(s)=>t.projects.update(s),delete:async(s)=>t.projects.delete(s)},messages:{list:async(s)=>t.messages.list(s),append:async(s)=>sx(t,await t.messages.append(V0(s)))},threads:{list:async(s={})=>t.threads.list(await K0(e.credentialProvider,s)),get:async(s)=>t.threads.get(s),getStatus:async(s)=>t.threads.getStatus(s),stop:async(s)=>t.threads.stop(s),create:async(s)=>sx(t,await t.threads.create(await W0(e.credentialProvider,s))),update:async(s)=>t.threads.update(s),fork:async(s)=>t.threads.fork(s),setVisibility:async(s)=>t.threads.setVisibility(s),createShareLink:async(s)=>t.threads.createShareLink(s),listShareLinks:async(s)=>t.threads.listShareLinks(s),revokeShareLink:async(s)=>t.threads.revokeShareLink(s),stream:async(s)=>r.streamThread(s)},runs:{list:async(s={})=>t.runs.list(await q0(e.credentialProvider,s)),listForThread:async(s)=>t.runs.listForThread(s),get:async(s)=>t.runs.get(s),cancel:async(s)=>t.runs.cancel(s),stream:async(s)=>r.streamRun(s)},logSources:{listProviders:async()=>t.logSources.listProviders({}),list:async(s={})=>t.logSources.list(await U(e.credentialProvider,s)),get:async(s)=>t.logSources.get(s),create:async(s)=>t.logSources.create(await U(e.credentialProvider,s)),update:async(s)=>t.logSources.update(s),delete:async(s)=>t.logSources.delete(s),verify:async(s)=>t.logSources.verify(s)},logStreams:{list:async(s)=>t.logStreams.list(s),get:async(s)=>t.logStreams.get(s),create:async(s)=>t.logStreams.create(s),update:async(s)=>t.logStreams.update(s),delete:async(s)=>t.logStreams.delete(s),reassign:async(s)=>t.logStreams.reassign(s),createBatch:async(s)=>t.logStreams.createBatch(s),volumeStats:async(s)=>t.logStreams.volumeStats(s)},connectedAccounts:{beginConnect:async(s)=>t.connectedAccounts.beginConnect(await Q(e.credentialProvider,s,"connectedAccounts.beginConnect")),getConnectAttempt:async(s)=>t.connectedAccounts.getConnectAttempt(await Q(e.credentialProvider,s,"connectedAccounts.getConnectAttempt")),list:async(s={})=>t.connectedAccounts.list(await Q(e.credentialProvider,s,"connectedAccounts.list")),disconnect:async(s)=>t.connectedAccounts.disconnect(await Q(e.credentialProvider,s,"connectedAccounts.disconnect"))},integrations:{listProviders:async(s={})=>t.integrations.listProviders(await Q(e.credentialProvider,s,"integrations.listProviders")),listConnections:async(s={})=>t.integrations.listConnections(await Q(e.credentialProvider,s,"integrations.listConnections")),getConnection:async(s)=>t.integrations.getConnection(await Q(e.credentialProvider,s,"integrations.getConnection")),createConnection:async(s)=>t.integrations.createConnection(await Q(e.credentialProvider,s,"integrations.createConnection")),beginConnect:async(s)=>t.integrations.beginConnect(await Q(e.credentialProvider,s,"integrations.beginConnect")),getConnectAttempt:async(s)=>t.integrations.getConnectAttempt(await Q(e.credentialProvider,s,"integrations.getConnectAttempt")),disconnectConnection:async(s)=>t.integrations.disconnectConnection(await Q(e.credentialProvider,s,"integrations.disconnectConnection")),updateConnectionCredentials:async(s)=>t.integrations.updateConnectionCredentials(await Q(e.credentialProvider,s,"integrations.updateConnectionCredentials")),createSlackChannel:async(s)=>t.integrations.createSlackChannel(await Q(e.credentialProvider,s,"integrations.createSlackChannel")),getActiveCLIAttempt:async(s)=>t.integrations.getActiveCLIAttempt(await Q(e.credentialProvider,s,"integrations.getActiveCLIAttempt")),getLinearAutomationConfiguration:async(s)=>t.integrations.getLinearAutomationConfiguration(await Q(e.credentialProvider,s,"integrations.getLinearAutomationConfiguration")),updateLinearAutomationConfiguration:async(s)=>t.integrations.updateLinearAutomationConfiguration(await Q(e.credentialProvider,s,"integrations.updateLinearAutomationConfiguration")),getOrganizationExternalIdentityJitPolicy:async(s={})=>t.integrations.getOrganizationExternalIdentityJitPolicy(await Q(e.credentialProvider,s,"integrations.getOrganizationExternalIdentityJitPolicy")),updateOrganizationExternalIdentityJitPolicy:async(s)=>t.integrations.updateOrganizationExternalIdentityJitPolicy(await Q(e.credentialProvider,s,"integrations.updateOrganizationExternalIdentityJitPolicy")),getConnectionExternalIdentityJitPolicy:async(s)=>t.integrations.getConnectionExternalIdentityJitPolicy(await Q(e.credentialProvider,s,"integrations.getConnectionExternalIdentityJitPolicy")),updateConnectionExternalIdentityJitPolicy:async(s)=>t.integrations.updateConnectionExternalIdentityJitPolicy(await Q(e.credentialProvider,s,"integrations.updateConnectionExternalIdentityJitPolicy")),getMicrosoftTeamsAdminConsent:async(s)=>t.integrations.getMicrosoftTeamsAdminConsent(await Q(e.credentialProvider,s,"integrations.getMicrosoftTeamsAdminConsent")),getSlackConfiguration:async(s)=>t.integrations.getSlackConfiguration(await Q(e.credentialProvider,s,"integrations.getSlackConfiguration")),updateSlackConfiguration:async(s)=>t.integrations.updateSlackConfiguration(await Q(e.credentialProvider,s,"integrations.updateSlackConfiguration")),listSlackChannelProjectMappings:async(s)=>t.integrations.listSlackChannelProjectMappings(await Q(e.credentialProvider,s,"integrations.listSlackChannelProjectMappings")),setSlackChannelProjectMapping:async(s)=>t.integrations.setSlackChannelProjectMapping(await Q(e.credentialProvider,s,"integrations.setSlackChannelProjectMapping")),deleteSlackChannelProjectMapping:async(s)=>t.integrations.deleteSlackChannelProjectMapping(await Q(e.credentialProvider,s,"integrations.deleteSlackChannelProjectMapping"))},mcpConnectors:{list:async(s={})=>t.mcpConnectors.list(await U(e.credentialProvider,s)),get:async(s)=>t.mcpConnectors.get(await U(e.credentialProvider,s)),details:async(s)=>t.mcpConnectors.details(await U(e.credentialProvider,s)),listProviders:async()=>t.mcpConnectors.listProviders({}),search:async(s={})=>t.mcpConnectors.search(await U(e.credentialProvider,s)),describe:async(s)=>t.mcpConnectors.describe(await U(e.credentialProvider,s)),call:async(s)=>t.mcpConnectors.call(await U(e.credentialProvider,s)),create:async(s)=>t.mcpConnectors.create(await U(e.credentialProvider,s)),update:async(s)=>t.mcpConnectors.update(await U(e.credentialProvider,s)),disconnect:async(s)=>{await t.mcpConnectors.disconnect(await U(e.credentialProvider,s))},setReadOnly:async(s)=>t.mcpConnectors.setReadOnly(await U(e.credentialProvider,s)),beginOAuthInstall:async(s)=>t.mcpConnectors.beginOAuthInstall(await U(e.credentialProvider,s)),getOAuthInstallAttempt:async(s)=>t.mcpConnectors.getOAuthInstallAttempt(await U(e.credentialProvider,s))},sandboxEnvironmentVariables:{delete:async(s)=>t.sandboxEnvironmentVariables.delete(await U(e.credentialProvider,s)),get:async(s)=>t.sandboxEnvironmentVariables.get(await U(e.credentialProvider,s)),list:async(s={})=>t.sandboxEnvironmentVariables.list(await U(e.credentialProvider,s)),upsert:async(s)=>t.sandboxEnvironmentVariables.upsert(await U(e.credentialProvider,s))},sandboxInitScript:{get:async(s={})=>t.sandboxInitScript.get(await U(e.credentialProvider,s)),upsert:async(s)=>t.sandboxInitScript.upsert(await U(e.credentialProvider,s)),delete:async(s={})=>t.sandboxInitScript.delete(await U(e.credentialProvider,s))},sandboxClis:{delete:async(s)=>t.sandboxClis.deleteCli(await U(e.credentialProvider,s)),listConnections:async(s={})=>t.sandboxClis.listConnections(await U(e.credentialProvider,s)),listTypes:async()=>t.sandboxClis.listTypes({}),test:async(s)=>t.sandboxClis.testCli(await U(e.credentialProvider,s)),upsert:async(s)=>t.sandboxClis.upsertCli(await U(e.credentialProvider,s)),verify:async(s)=>t.sandboxClis.verify(await U(e.credentialProvider,s))},memory:{list:async(s={})=>t.memory.list(await U(e.credentialProvider,s)),get:async(s)=>t.memory.get(await U(e.credentialProvider,s)),put:async(s)=>t.memory.put(await U(e.credentialProvider,s)),create:async(s)=>t.memory.create(await U(e.credentialProvider,s)),update:async(s)=>t.memory.update(await U(e.credentialProvider,s)),search:async(s)=>t.memory.search(await U(e.credentialProvider,s)),delete:async(s)=>t.memory.delete(await U(e.credentialProvider,s))},supportTickets:{create:async(s)=>t.supportTickets.create(await U(e.credentialProvider,await Q(e.credentialProvider,s,"supportTickets.create"))),availability:async()=>t.supportTickets.availability({})},signalDefinitions:{list:async(s={})=>t.signalDefinitions.list(await U(e.credentialProvider,s)),get:async(s)=>t.signalDefinitions.get(await U(e.credentialProvider,s)),create:async(s)=>t.signalDefinitions.create(await U(e.credentialProvider,s)),update:async(s)=>t.signalDefinitions.update(await U(e.credentialProvider,s)),disable:async(s)=>t.signalDefinitions.disable(await U(e.credentialProvider,s)),delete:async(s)=>t.signalDefinitions.delete(await U(e.credentialProvider,s))},scripts:{list:async(s={})=>t.scripts.list(await U(e.credentialProvider,s)),get:async(s)=>t.scripts.get(await U(e.credentialProvider,s)),create:async(s)=>t.scripts.create(await U(e.credentialProvider,s)),update:async(s)=>t.scripts.update(await U(e.credentialProvider,s)),delete:async(s)=>t.scripts.delete(await U(e.credentialProvider,s))},issues:{create:async(s)=>t.issues.create(await U(e.credentialProvider,s)),list:async(s={})=>t.issues.list(await U(e.credentialProvider,s)),search:async(s={})=>t.issues.search(await U(e.credentialProvider,s)),get:async(s)=>t.issues.get(s),getRejectionContext:async(s)=>t.issues.getRejectionContext(s),reject:async(s)=>t.issues.reject(s),resolve:async(s)=>t.issues.resolve(s),ignore:async(s)=>t.issues.ignore(s),reopen:async(s)=>t.issues.reopen(s),mute:async(s)=>t.issues.mute(s),unmute:async(s)=>t.issues.unmute(s),reassignAndReopen:async(s)=>t.issues.reassignAndReopen(s)},workItems:{create:async(s)=>t.workItems.create(await Q(e.credentialProvider,s,"work-items.create")),comment:async(s)=>t.workItems.comment(await Q(e.credentialProvider,s,"work-items.comment")),transition:async(s)=>t.workItems.transition(await Q(e.credentialProvider,s,"work-items.transition"))},pullRequests:{list:async(s={})=>t.pullRequests.list(await U(e.credentialProvider,s))},components:{list:async(s={})=>t.components.list(await U(e.credentialProvider,s)),get:async(s)=>t.components.get(s),register:async(s)=>t.components.register(await U(e.credentialProvider,s)),deregister:async(s)=>t.components.deregister(s),rename:async(s)=>t.components.rename(s),assignTeam:async(s)=>t.components.assignTeam(s),reactivationPreview:async(s)=>t.components.reactivationPreview(s),reactivate:async(s)=>t.components.reactivate(s),mergePreview:async(s)=>t.components.mergePreview(await U(e.credentialProvider,s)),merge:async(s)=>t.components.merge(await U(e.credentialProvider,s)),relationships:{list:async(s={})=>t.components.relationships.list(await U(e.credentialProvider,s)),preview:async(s)=>t.components.relationships.preview(await U(e.credentialProvider,s)),add:async(s)=>t.components.relationships.add(await U(e.credentialProvider,s)),remove:async(s)=>t.components.relationships.remove(await U(e.credentialProvider,s))},incidents:{list:async(s={})=>t.components.incidents.list(await U(e.credentialProvider,s))},timeline:async(s)=>t.components.timeline(s)},billing:{getSummary:async(s={})=>t.billing.getSummary(await Q(e.credentialProvider,s,"billing.getSummary")),getUsage:async(s={})=>t.billing.getUsage(await Q(e.credentialProvider,s,"billing.getUsage")),getAccruedUsageCharges:async(s={})=>t.billing.getAccruedUsageCharges(await Q(e.credentialProvider,s,"billing.getAccruedUsageCharges")),listUsageInvoices:async(s={})=>t.billing.listUsageInvoices(await Q(e.credentialProvider,s,"billing.listUsageInvoices")),listTransactions:async(s={})=>t.billing.listTransactions(await Q(e.credentialProvider,s,"billing.listTransactions")),previewSubscriptionCancellation:async(s={})=>t.billing.previewSubscriptionCancellation(await Q(e.credentialProvider,s,"billing.previewSubscriptionCancellation")),scheduleSubscriptionCancellation:async(s={})=>t.billing.scheduleSubscriptionCancellation(await Q(e.credentialProvider,s,"billing.scheduleSubscriptionCancellation")),resumeSubscriptionCancellation:async(s={})=>t.billing.resumeSubscriptionCancellation(await Q(e.credentialProvider,s,"billing.resumeSubscriptionCancellation")),getAutoTopUp:async(s={})=>t.billing.getAutoTopUp(await Q(e.credentialProvider,s,"billing.getAutoTopUp")),updateAutoTopUp:async(s)=>t.billing.updateAutoTopUp(await Q(e.credentialProvider,s,"billing.updateAutoTopUp")),purchaseCredits:async(s)=>t.billing.purchaseCredits(await Q(e.credentialProvider,s,"billing.purchaseCredits")),listPlans:async(s={})=>t.billing.listPlans(await Q(e.credentialProvider,s,"billing.listPlans")),previewPlanChange:async(s)=>t.billing.previewPlanChange(await Q(e.credentialProvider,s,"billing.previewPlanChange")),changePlan:async(s)=>t.billing.changePlan(await Q(e.credentialProvider,s,"billing.changePlan")),createCheckoutSession:async(s)=>t.billing.createCheckoutSession(await Q(e.credentialProvider,s,"billing.createCheckoutSession")),getCheckoutSessionStatus:async(s)=>t.billing.getCheckoutSessionStatus(await Q(e.credentialProvider,s,"billing.getCheckoutSessionStatus")),createPortalSession:async(s={})=>t.billing.createPortalSession(await Q(e.credentialProvider,s,"billing.createPortalSession")),getPaymentMethod:async(s={})=>t.billing.getPaymentMethod(await Q(e.credentialProvider,s,"billing.getPaymentMethod"))},tasks:{list:async(s={})=>t.tasks.list(await Un(e.credentialProvider,s,"tasks.list")),skip:async(s)=>t.tasks.skip(await lo(e.credentialProvider,await U(e.credentialProvider,s))),unskip:async(s)=>t.tasks.unskip(await lo(e.credentialProvider,await U(e.credentialProvider,s))),create:async(s)=>o(s,"tasks.create"),comment:async(s)=>i(s,"tasks.comment"),transition:async(s)=>a(s,"tasks.transition")},recommendations:{list:async(s={})=>t.recommendations.list(await U(e.credentialProvider,s))},repos:{list:async(s={})=>t.repos.list(await U(e.credentialProvider,s)),add:async(s)=>t.repos.add(await U(e.credentialProvider,s)),remove:async(s)=>t.repos.remove(await U(e.credentialProvider,s))},notificationDeliveryRules:{list:async(s={})=>t.notificationDeliveryRules.list(await U(e.credentialProvider,s)),options:async(s={})=>t.notificationDeliveryRules.options(await U(e.credentialProvider,s)),create:async(s)=>t.notificationDeliveryRules.create(await U(e.credentialProvider,s)),update:async(s)=>t.notificationDeliveryRules.update(await U(e.credentialProvider,s)),delete:async(s)=>t.notificationDeliveryRules.delete(await U(e.credentialProvider,s))},taskCreationRules:{list:async(s={})=>t.taskCreationRules.list(await U(e.credentialProvider,s)),get:async(s)=>t.taskCreationRules.get(await U(e.credentialProvider,s)),create:async(s)=>t.taskCreationRules.create(await U(e.credentialProvider,s)),update:async(s)=>t.taskCreationRules.update(await U(e.credentialProvider,s)),delete:async(s)=>t.taskCreationRules.delete(await U(e.credentialProvider,s)),reorder:async(s)=>t.taskCreationRules.reorder(await U(e.credentialProvider,s))},notificationChannels:{getProject:async(s={})=>t.notificationChannels.getProject(await U(e.credentialProvider,s))},webhooks:{list:async()=>t.webhooks.list({}),get:async(s)=>t.webhooks.get(s),create:async(s)=>t.webhooks.create(s),update:async(s)=>t.webhooks.update(s),delete:async(s)=>t.webhooks.delete(s),rotateSecret:async(s)=>t.webhooks.rotateSecret(s),enable:async(s)=>t.webhooks.enable(s),test:async(s)=>t.webhooks.test(s),subscribe:async(s)=>t.webhooks.subscribe(await U(e.credentialProvider,s)),unsubscribe:async(s)=>t.webhooks.unsubscribe(s),listDeliveries:async(s)=>t.webhooks.listDeliveries(s)}}},Tb=async(e={})=>{let t=await mx(e.fetch)(dx(e.apiBaseUrl??cx,"/device/code"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:e.clientId??lx,...e.scope?{scope:e.scope}:{}})}),n=await t.json();if(!t.ok)throw Y0(n,t.status);let r=n;return{deviceCode:Xr(r.device_code,"device_code"),userCode:Xr(r.user_code,"user_code"),verificationUri:Xr(r.verification_uri,"verification_uri"),verificationUriComplete:Xr(r.verification_uri_complete,"verification_uri_complete"),expiresIn:Ab(r.expires_in,"expires_in"),interval:Ab(r.interval,"interval")}},_b=async(e)=>{let t=await mx(e.fetch)(dx(e.apiBaseUrl??cx,"/device/token"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:F0,device_code:e.deviceCode,client_id:e.clientId??lx})}),n=await t.json();if(t.ok){let o=n;return{status:"authorized",accessToken:Xr(o.access_token,"access_token"),tokenType:Xr(o.token_type,"token_type"),expiresIn:Ab(o.expires_in,"expires_in"),scope:typeof o.scope==="string"?o.scope:""}}let r=px(n);if(!r)throw Error(`Device authorization failed with status ${t.status}`);if(r.error==="authorization_pending")return{status:"pending"};if(r.error==="slow_down")return{status:"pending",interval:10};if(r.error==="access_denied")return{status:"denied",message:r.errorDescription};if(r.error==="expired_token"||r.error==="invalid_grant")return{status:"expired",message:r.errorDescription};throw Error(r.errorDescription)},B0=(e)=>{let t=e.replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`},dx=(e,t)=>`${e.replace(/\/+$/,"")}/api/auth${t}`,G0=async(e,t)=>Q(e,t,"projects.list"),lo=async(e,t)=>{let n=t.organizationId??await e.getOrganizationId?.();return n?{...t,organizationId:n}:t},Q=async(e,t,n)=>{let r=t.organizationId??await e.getOrganizationId?.();if(!r)throw new Ye("BAD_REQUEST",{message:"Organization ID is required",data:{operationId:n,missingContext:["organizationId"]},status:400});return{...t,organizationId:r}},ax=async(e,t)=>t.organizationId!==void 0?t:lo(e,await U(e,t)),U=async(e,t)=>{let n=t.projectId??await e.getProjectId?.();return n?{...t,projectId:n}:t},Un=async(e,t,n)=>{let r=t.projectId??await e.getProjectId?.();if(!r)throw new Ye("BAD_REQUEST",{message:"Project ID is required",data:{operationId:n,missingContext:["projectId"]},status:400});return{...t,projectId:r}},K0=async(e,t)=>{let n=t.projectId??await e.getProjectId?.();return n?{...t,projectId:n}:t},q0=async(e,t)=>{let n=t.projectId??await e.getProjectId?.();return n?{...t,projectId:n}:t},W0=async(e,t)=>{let n=t.projectId??await e.getProjectId?.();return n?{...t,projectId:n}:t},V0=(e)=>({threadId:e.threadId,message:e.message,wait:e.wait??!0,timeoutSeconds:e.timeoutSeconds??20,...e.automationId!==void 0?{automationId:e.automationId}:{}}),H0=(e)=>{if(!e||typeof e!=="object")return null;let t=e;if(typeof t.code!=="string"||typeof t.message!=="string"||typeof t.operationId!=="string")return null;return{code:t.code,message:t.message,operationId:t.operationId,missingContext:Array.isArray(t.missingContext)?t.missingContext.filter((n)=>typeof n==="string"):[],...typeof t.reason==="string"?{reason:t.reason}:{},...typeof t.entitlementId==="string"?{entitlementId:t.entitlementId}:{},...typeof t.planSlug==="string"||t.planSlug===null?{planSlug:t.planSlug}:{},...typeof t.limit==="boolean"||typeof t.limit==="string"||typeof t.limit==="number"||t.limit===null?{limit:t.limit}:{},...typeof t.current==="number"?{current:t.current}:{},...typeof t.actionPath==="string"?{actionPath:t.actionPath}:{},...typeof t.retryAfterSeconds==="number"?{retryAfterSeconds:t.retryAfterSeconds}:{},...Array.isArray(t.issues)?{issues:J0(t.issues)}:{},...Z0(t.details),...Array.isArray(t.diagnostics)?{diagnostics:t.diagnostics}:{},...typeof t.currentRevision==="number"?{currentRevision:t.currentRevision}:{}}},Z0=(e)=>{if(!e||typeof e!=="object"||Array.isArray(e))return{};let t=Object.fromEntries(Object.entries(e).filter((n)=>typeof n[1]==="string"));return Object.keys(t).length>0?{details:t}:{}},J0=(e)=>e.flatMap((t)=>{if(!t||typeof t!=="object")return[];let{path:n,message:r}=t;if(typeof r!=="string")return[];return[{message:r,path:Array.isArray(n)?n.filter((o)=>typeof o==="string"):[]}]}),px=(e)=>{if(!e||typeof e!=="object")return null;let t=e;if(typeof t.error!=="string"||typeof t.error_description!=="string")return null;return{error:t.error,errorDescription:t.error_description}},Y0=(e,t)=>{let n=px(e);return Error(n?.errorDescription??`Device authorization failed with status ${t}`)},mx=(e)=>e??globalThis.fetch,sx=(e,t)=>({result:t,poll:()=>e.runs.get({runId:t.runId}),waitForCompletion:async(n={})=>X0(e,t,n)}),X0=async(e,t,n)=>{if(t.completed)return t;let r=n.intervalMs??2000,o=Date.now(),i=t;while(!i.completed){if(n.timeoutMs!==void 0&&Date.now()-o>=n.timeoutMs)return i;await Q0(r),i=await e.runs.get({runId:i.runId})}return i},Q0=async(e)=>{await new Promise((t)=>globalThis.setTimeout(t,e))},Xr=(e,t)=>{if(typeof e==="string")return e;throw Error(`Expected '${t}' to be a string.`)},Ab=(e,t)=>{if(typeof e==="number")return e;throw Error(`Expected '${t}' to be a number.`)};var jb=L(()=>{vr();aw();qO();Ob();rx();Ob()});var Re=(e)=>({success:!0,value:e}),we=(e,t,n)=>({success:!1,error:e,...t!==void 0&&{statusCode:t},...n!==void 0&&{errorPayload:n}}),eF=(e)=>{if(e===void 0)return"NETWORK_ERROR";if(e===401)return"UNAUTHORIZED";if(e===403)return"FORBIDDEN";if(e===404)return"NOT_FOUND";if(e===402)return"PAYMENT_REQUIRED";if(e===429)return"TOO_MANY_REQUESTS";if(e>=500)return"SERVER_ERROR";return"REQUEST_FAILED"},tF="Your session has expired or is invalid. Run 'sazabi auth sign-in' to sign in again.",nF,gx="settings",hx=(e)=>{gx=e},oF=()=>nF[gx],f=(e,t,n,{signInOnUnauthorized:r=!0}={})=>{if(!e.success){let o=r&&e.statusCode===401?oF():`${t}: ${e.error}`;if(n)return h(e.errorPayload??{code:eF(e.statusCode),message:o,operationId:null});return g(o)}return e.value};var te=L(()=>{H();nF={settings:tF,environment:"Sazabi rejected the token in SAZABI_TOKEN: it's expired, invalid, or can't be used for this command. Set a valid token, or unset SAZABI_TOKEN and run 'sazabi auth sign-in' to sign in.",flag:"Sazabi rejected the token passed with --token: it's expired, invalid, or can't be used for this command. Pass a valid token, or drop --token and run 'sazabi auth sign-in' to sign in."}});var Mn=()=>Ed({moduleUrl:import.meta.url});var qa=L(()=>{H()});var rF="https://api.sazabi.com",iF,Rb,aF=30,sF=(e)=>new Promise((t)=>setTimeout(t,e)),w=async(e)=>{for(let t=0;;t+=1)try{return Re(await e())}catch(n){let r=cF(n),o=lF(n),i=r?.retryAfterSeconds;if(o===429&&t===0&&i!==void 0&&i<=aF&&process.env.SAZABI_NO_RETRY!=="1"){process.stderr.write(`Rate limited; retrying in ~${i}s…
|
|
117
117
|
`),await sF(i*1000);continue}let a=n instanceof Error?n.message:String(n);if(i!==void 0)a+=` Retry in ~${i}s.`;return we(a,o,r)}},cF=(e)=>{if(!e||typeof e!=="object")return;let t=e;if(typeof t.code!=="string"||typeof t.message!=="string"||!t.data||typeof t.data!=="object")return;let n=t.data;if(typeof n.operationId!=="string")return;let r=Object.fromEntries(iF.flatMap((o)=>typeof n[o]==="string"?[[o,n[o]]]:[]));return{code:t.code,message:t.message,operationId:n.operationId,...typeof n.reason==="string"?{reason:n.reason}:{},...typeof n.entitlementId==="string"?{entitlementId:n.entitlementId}:{},...typeof n.planSlug==="string"||n.planSlug===null?{planSlug:n.planSlug}:{},...typeof n.limit==="boolean"||typeof n.limit==="string"||typeof n.limit==="number"||n.limit===null?{limit:n.limit}:{},...typeof n.current==="number"?{current:n.current}:{},...typeof n.actionPath==="string"?{actionPath:n.actionPath}:{},...typeof n.retryAfterSeconds==="number"?{retryAfterSeconds:n.retryAfterSeconds}:{},...Array.isArray(n.missingContext)?{missingContext:n.missingContext.filter((o)=>typeof o==="string")}:{},...Array.isArray(n.issues)?{issues:n.issues.flatMap((o)=>{if(!o||typeof o!=="object")return[];let{path:i,message:a}=o;if(typeof a!=="string")return[];return[{message:a,path:Array.isArray(i)?i.filter((s)=>typeof s==="string"):[]}]})}:{},...Object.keys(r).length>0?{details:r}:{}}},fx=(e)=>{let t=e.errorPayload;if(!t||!Array.isArray(t.issues))return[];return t.issues.map((n)=>n.message).filter((n)=>n.length>0)},lF=(e)=>{if(!e||typeof e!=="object")return;let t=e;return typeof t.status==="number"?t.status:void 0},Fn=(e)=>{let t=ux({apiBaseUrl:e.baseUrl??rF,clientSource:"cli",clientVersion:Mn(),sandboxActorDescriptor:e.sandboxActorDescriptor,credentialProvider:{getToken:()=>e.token,getOrganizationId:()=>e.organizationId,getProjectId:()=>e.projectId},intakeBaseUrl:e.intakeBaseUrl,tailBaseUrl:e.tailBaseUrl});return{me:()=>{let n=`${e.token}::${e.baseUrl??""}`,r=Rb.get(n);if(r)return r;let o=w(()=>t.me()).then((i)=>{if(!i.success)Rb.delete(n);return i});return Rb.set(n,o),o},artifacts:{list:(n={})=>w(()=>t.artifacts.list(n)),listIssueArtifacts:(n)=>w(()=>t.artifacts.listIssueArtifacts(n)),get:(n)=>w(()=>t.artifacts.get(n)),download:(n)=>w(()=>t.artifacts.download(n)),delete:(n)=>w(()=>t.artifacts.delete(n))},automations:{list:(n={})=>w(()=>t.automations.list(n)),get:(n)=>w(()=>t.automations.get({automationId:n})),create:(n)=>w(()=>t.automations.create(n)),update:(n)=>w(()=>t.automations.update(n)),enable:(n)=>w(()=>t.automations.enable({automationId:n})),disable:(n)=>w(()=>t.automations.disable({automationId:n})),runs:{list:(n,r={})=>w(()=>t.automations.runs.list({automationId:n,...r})),get:(n,r)=>w(()=>t.automations.runs.get({automationId:n,runId:r})),logs:(n,r)=>w(()=>t.automations.runs.logs({automationId:n,runId:r}))}},automationTemplates:{list:()=>w(()=>t.automationTemplates.list())},logs:{tail:(n)=>w(()=>t.logs.tail(n)),forward:(n)=>w(()=>t.logs.forward(n)),ask:(n)=>w(()=>t.logs.ask(n)),executeQuery:(n)=>w(()=>t.logs.executeQuery(n))},organizations:{list:()=>w(()=>t.organizations.list()),get:(n)=>w(()=>t.organizations.get({organizationId:n})),create:(n)=>w(()=>t.organizations.create({name:n})),rename:(n,r)=>w(()=>t.organizations.update({organizationId:r,name:n}))},members:{list:(n={})=>w(()=>t.members.list(n)),updateRole:(n,r,o)=>w(()=>t.members.updateRole({organizationId:o,member:n,role:r})),remove:(n,r)=>w(()=>t.members.remove({organizationId:r,member:n})),invite:(n)=>w(()=>t.members.invite({organizationId:n.organizationId,email:n.email,role:n.role})),listInvitations:(n)=>w(()=>t.members.listInvitations({organizationId:n})),revokeInvitation:(n)=>w(()=>t.members.revokeInvitation({organizationId:n.organizationId,invitationId:n.invitationId}))},teams:{list:(n={})=>w(()=>t.teams.list(n)),create:(n,r,o)=>w(()=>t.teams.create({organizationId:o,name:n,...r!==void 0?{description:r}:{}})),update:(n,r,o)=>w(()=>t.teams.update({organizationId:o,teamId:n,...r.name!==void 0?{name:r.name}:{},...r.description!==void 0?{description:r.description}:{}})),delete:(n,r)=>w(()=>t.teams.delete({organizationId:r,teamId:n})),addMember:(n,r,o)=>w(()=>t.teams.addMember({organizationId:o,teamId:n,userId:r})),removeMember:(n,r,o)=>w(()=>t.teams.removeMember({organizationId:o,teamId:n,userId:r})),listMembers:(n,r)=>w(()=>t.teams.listMembers({organizationId:r,teamId:n}))},projects:{list:(n={})=>w(()=>t.projects.list(n)),get:(n)=>w(()=>t.projects.get({projectId:n})),create:(n)=>w(()=>t.projects.create(n))},supportTickets:{create:(n)=>w(()=>t.supportTickets.create(n)),availability:()=>w(()=>t.supportTickets.availability())},threads:{list:(n={})=>w(()=>t.threads.list(n)),get:(n)=>w(()=>t.threads.get({threadId:n})),create:(n)=>w(()=>t.threads.create(n)),getStatus:(n)=>w(()=>t.threads.getStatus({threadId:n})),update:(n,r)=>w(()=>t.threads.update({threadId:n,status:r})),fork:(n,r)=>w(()=>t.threads.fork({threadId:n,messageId:r})),setVisibility:(n,r)=>w(()=>t.threads.setVisibility({threadId:n,visibility:r})),createShareLink:(n)=>w(()=>t.threads.createShareLink({threadId:n})),listShareLinks:(n)=>w(()=>t.threads.listShareLinks({threadId:n})),revokeShareLink:(n,r)=>w(()=>t.threads.revokeShareLink({threadId:n,shareId:r})),stop:(n)=>w(()=>t.threads.stop({threadId:n})),stream:(n)=>w(()=>t.threads.stream(n))},messages:{list:(n,r={})=>w(()=>t.messages.list({threadId:n,...r})),append:(n,r,o,i,a,s)=>w(()=>t.messages.append({threadId:n,message:r,wait:o,timeoutSeconds:i,...a!==void 0?{automationId:a}:{},...s?{ambientServiceRun:s}:{}}))},runs:{list:(n={})=>w(()=>t.runs.list(n)),get:(n)=>w(()=>t.runs.get({runId:n})),cancel:(n)=>w(()=>t.runs.cancel({runId:n})),stream:(n)=>w(()=>t.runs.stream(n))},search:{threads:(n)=>w(()=>t.search.threads(n)),messages:(n)=>w(()=>t.search.messages(n))},publicKeys:{list:(n)=>w(()=>t.publicKeys.list(n)),get:(n,r)=>w(()=>t.publicKeys.get(r?{keyId:n,projectId:r}:{keyId:n})),ensureLogForwarding:(n)=>w(()=>t.publicKeys.ensureLogForwarding(n)),update:(n)=>w(()=>t.publicKeys.update(n)),deactivate:(n)=>w(()=>t.publicKeys.deactivate(n))},secretKeys:{list:(n)=>w(()=>t.secretKeys.list(n)),get:(n)=>w(()=>t.secretKeys.get({keyId:n})),create:(n)=>w(()=>t.secretKeys.create(n)),update:(n)=>w(()=>t.secretKeys.update(n)),delete:(n)=>w(()=>t.secretKeys.delete(n))},issues:{create:(n)=>w(()=>t.issues.create(n)),list:(n={})=>w(()=>t.issues.list(n)),search:(n={})=>w(()=>t.issues.search(n)),get:(n)=>w(()=>t.issues.get({issueId:n})),getRejectionContext:(n)=>w(()=>t.issues.getRejectionContext({issueId:n})),reject:(n,r)=>w(()=>t.issues.reject({issueId:n,...r})),resolve:(n)=>w(()=>t.issues.resolve({issueId:n})),ignore:(n)=>w(()=>t.issues.ignore({issueId:n})),reopen:(n)=>w(()=>t.issues.reopen({issueId:n})),mute:(n)=>w(()=>t.issues.mute({issueId:n})),unmute:(n)=>w(()=>t.issues.unmute({issueId:n}))},pullRequests:{list:(n={})=>w(()=>t.pullRequests.list(n))},components:{list:(n={})=>w(()=>t.components.list(n)),get:(n)=>w(()=>t.components.get({componentId:n})),register:(n)=>w(()=>t.components.register(n)),deregister:(n)=>w(()=>t.components.deregister(n)),rename:(n)=>w(()=>t.components.rename(n)),reactivationPreview:(n)=>w(()=>t.components.reactivationPreview(n)),reactivate:(n)=>w(()=>t.components.reactivate(n)),mergePreview:(n)=>w(()=>t.components.mergePreview(n)),merge:(n)=>w(()=>t.components.merge(n)),relationships:{list:(n={})=>w(()=>t.components.relationships.list(n)),preview:(n)=>w(()=>t.components.relationships.preview(n)),add:(n)=>w(()=>t.components.relationships.add(n)),remove:(n)=>w(()=>t.components.relationships.remove(n))},incidents:{list:(n={})=>w(()=>t.components.incidents.list(n))},timeline:(n)=>w(()=>t.components.timeline(n))},billing:{getSummary:(n={})=>w(()=>t.billing.getSummary(n)),getUsage:(n={})=>w(()=>t.billing.getUsage(n)),getAccruedUsageCharges:(n={})=>w(()=>t.billing.getAccruedUsageCharges(n)),listUsageInvoices:(n={})=>w(()=>t.billing.listUsageInvoices(n)),listTransactions:(n={})=>w(()=>t.billing.listTransactions(n)),previewSubscriptionCancellation:()=>w(()=>t.billing.previewSubscriptionCancellation()),scheduleSubscriptionCancellation:()=>w(()=>t.billing.scheduleSubscriptionCancellation()),resumeSubscriptionCancellation:()=>w(()=>t.billing.resumeSubscriptionCancellation()),getAutoTopUp:(n={})=>w(()=>t.billing.getAutoTopUp(n)),updateAutoTopUp:(n)=>w(()=>t.billing.updateAutoTopUp(n)),purchaseCredits:(n)=>w(()=>t.billing.purchaseCredits(n)),listPlans:(n={})=>w(()=>t.billing.listPlans(n)),previewPlanChange:(n)=>w(()=>t.billing.previewPlanChange(n)),changePlan:(n)=>w(()=>t.billing.changePlan(n)),createCheckoutSession:(n)=>w(()=>t.billing.createCheckoutSession(n)),getCheckoutSessionStatus:(n)=>w(()=>t.billing.getCheckoutSessionStatus(n)),createPortalSession:(n={})=>w(()=>t.billing.createPortalSession(n)),getPaymentMethod:(n={})=>w(()=>t.billing.getPaymentMethod(n))},tasks:{list:(n={})=>w(()=>t.tasks.list(n)),skip:(n)=>w(()=>t.tasks.skip(n)),unskip:(n)=>w(()=>t.tasks.unskip(n)),create:(n)=>w(()=>t.tasks.create(n)),comment:(n)=>w(()=>t.tasks.comment(n)),transition:(n)=>w(()=>t.tasks.transition(n))},recommendations:{list:(n={})=>w(()=>t.recommendations.list(n))},repos:{list:(n={})=>w(()=>t.repos.list(n)),add:(n)=>w(()=>t.repos.add(n)),remove:(n)=>w(()=>t.repos.remove(n))},onboarding:{getState:(n={})=>w(()=>t.onboarding.getState(n)),skipSampleIssue:(n)=>w(()=>t.onboarding.skipSampleIssue(n)),continueWithFree:(n)=>w(()=>t.onboarding.continueWithFree(n)),ensureDefaultProject:(n)=>w(()=>t.onboarding.ensureDefaultProject(n)),completeSampleIssue:(n)=>w(()=>t.onboarding.completeSampleIssue(n)),finish:(n)=>w(()=>t.onboarding.finish(n))},notificationDeliveryRules:{list:()=>w(()=>t.notificationDeliveryRules.list()),options:()=>w(()=>t.notificationDeliveryRules.options()),create:(n)=>w(()=>t.notificationDeliveryRules.create(n)),update:(n)=>w(()=>t.notificationDeliveryRules.update(n)),delete:(n)=>w(()=>t.notificationDeliveryRules.delete({ruleId:n}))},taskCreationRules:{list:(n)=>w(()=>t.taskCreationRules.list(n?.projectId?{projectId:n.projectId}:{})),get:(n)=>w(()=>t.taskCreationRules.get({ruleId:n.ruleId,projectId:n.projectId})),create:(n)=>w(()=>t.taskCreationRules.create(n)),update:(n)=>w(()=>t.taskCreationRules.update(n)),delete:(n)=>w(()=>t.taskCreationRules.delete({ruleId:n.ruleId,projectId:n.projectId})),reorder:(n)=>w(()=>t.taskCreationRules.reorder({orderedRuleIds:n.orderedRuleIds,projectId:n.projectId}))},notificationChannels:{getProject:()=>w(()=>t.notificationChannels.getProject())},webhooks:{list:()=>w(()=>t.webhooks.list()),get:(n)=>w(()=>t.webhooks.get(n)),create:(n)=>w(()=>t.webhooks.create(n)),update:(n)=>w(()=>t.webhooks.update(n)),delete:(n)=>w(()=>t.webhooks.delete(n)),rotateSecret:(n)=>w(()=>t.webhooks.rotateSecret(n)),enable:(n)=>w(()=>t.webhooks.enable(n)),test:(n)=>w(()=>t.webhooks.test(n)),subscribe:(n)=>w(()=>t.webhooks.subscribe(n)),unsubscribe:(n)=>w(()=>t.webhooks.unsubscribe(n)),listDeliveries:(n)=>w(()=>t.webhooks.listDeliveries(n))},logSources:{listProviders:()=>w(()=>t.logSources.listProviders()),list:(n)=>w(()=>t.logSources.list(n)),get:(n)=>w(()=>t.logSources.get({logSourceId:n})),create:(n)=>w(()=>t.logSources.create(n)),update:(n)=>w(()=>t.logSources.update(n)),delete:(n)=>w(()=>t.logSources.delete({logSourceId:n}))},logStreams:{list:(n)=>w(()=>t.logStreams.list({logSourceId:n})),get:(n)=>w(()=>t.logStreams.get({streamId:n})),create:(n)=>w(()=>t.logStreams.create(n)),update:(n)=>w(()=>t.logStreams.update(n)),delete:(n)=>w(()=>t.logStreams.delete({streamId:n})),reassign:(n)=>w(()=>t.logStreams.reassign(n))},integrations:{listProviders:()=>w(()=>t.integrations.listProviders()),listConnections:(n)=>w(()=>t.integrations.listConnections(n)),getConnection:(n)=>w(()=>t.integrations.getConnection({connectionId:n})),createConnection:(n)=>w(()=>t.integrations.createConnection(n)),beginConnect:(n)=>w(()=>t.integrations.beginConnect(n)),getConnectAttempt:(n)=>w(()=>t.integrations.getConnectAttempt({attemptId:n})),disconnectConnection:(n)=>w(()=>t.integrations.disconnectConnection({connectionId:n})),createSlackChannel:(n)=>w(()=>t.integrations.createSlackChannel(n)),updateConnectionCredentials:(n)=>w(()=>t.integrations.updateConnectionCredentials(n))},connectedAccounts:{beginConnect:(n)=>w(()=>t.connectedAccounts.beginConnect(n)),getConnectAttempt:(n)=>w(()=>t.connectedAccounts.getConnectAttempt({attemptId:n})),list:()=>w(()=>t.connectedAccounts.list({})),disconnect:(n)=>w(()=>t.connectedAccounts.disconnect(n))},mcpConnectors:{list:(n)=>w(()=>t.mcpConnectors.list(n)),get:(n)=>w(()=>t.mcpConnectors.get(n)),details:(n)=>w(()=>t.mcpConnectors.details(n)),listProviders:()=>w(()=>t.mcpConnectors.listProviders()),search:(n)=>w(()=>t.mcpConnectors.search(n)),call:(n)=>w(()=>t.mcpConnectors.call(n)),beginOAuthInstall:(n)=>w(()=>t.mcpConnectors.beginOAuthInstall(n)),getOAuthInstallAttempt:(n)=>w(()=>t.mcpConnectors.getOAuthInstallAttempt(n)),disconnect:(n)=>w(()=>t.mcpConnectors.disconnect(n)),update:(n)=>w(()=>t.mcpConnectors.update(n))},sandboxClis:{delete:(n)=>w(()=>t.sandboxClis.delete(n)),listConnections:(n)=>w(()=>t.sandboxClis.listConnections(n)),listTypes:()=>w(()=>t.sandboxClis.listTypes()),test:(n)=>w(()=>t.sandboxClis.test(n)),upsert:(n)=>w(()=>t.sandboxClis.upsert(n))},sandboxEnvironmentVariables:{delete:(n)=>w(()=>t.sandboxEnvironmentVariables.delete(n)),get:(n)=>w(()=>t.sandboxEnvironmentVariables.get(n)),list:(n)=>w(()=>t.sandboxEnvironmentVariables.list(n)),upsert:(n)=>w(()=>t.sandboxEnvironmentVariables.upsert(n))},memory:{list:(n={})=>w(()=>t.memory.list(n)),get:(n)=>w(()=>t.memory.get(n)),search:(n)=>w(()=>t.memory.search(n)),create:(n)=>w(()=>t.memory.create({kind:"note",...n})),update:(n)=>w(()=>t.memory.update(n)),delete:(n)=>w(()=>t.memory.delete(n))},signalDefinitions:{list:(n={})=>w(()=>t.signalDefinitions.list(n)),get:(n)=>w(()=>t.signalDefinitions.get({signalDefinitionId:n})),create:(n)=>w(()=>t.signalDefinitions.create(n)),update:(n,r={})=>w(()=>t.signalDefinitions.update({signalDefinitionId:n,...r})),disable:(n)=>w(()=>t.signalDefinitions.disable({signalDefinitionId:n}))},scripts:{list:(n={})=>w(()=>t.scripts.list(n)),get:(n)=>w(()=>t.scripts.get({name:n})),create:(n)=>w(()=>t.scripts.create(n)),update:(n,r={})=>w(()=>t.scripts.update({name:n,...r})),delete:(n)=>w(()=>t.scripts.delete({name:n}))}}};var Qr=L(()=>{jb();te();qa();iF=["canonicalTargetComponentId","canonicalComponentId","componentId"],Rb=new Map});var yx;var bx=L(()=>{yx={version:2,activeProfile:"default",profiles:{default:{}}}});import*as Bn from"node:fs";import*as vx from"node:os";import*as zb from"node:path";var ut=(e)=>{if(e===void 0||e===null)return;if(typeof e==="string")return e.length>0?e:void 0;return},Eb,ei,uF=()=>{if(!Bn.existsSync(Eb))Bn.mkdirSync(Eb,{recursive:!0,mode:448})},Lb,Sx=(e)=>{Lb=e},Ix=(e)=>({token:ut(e.token),activeOrganizationId:ut(e.activeOrganizationId??e.organizationId),organizationName:ut(e.organizationName),activeProjectId:ut(e.activeProjectId??e.defaultProjectId),apiBaseUrl:ut(e.apiBaseUrl),authBaseUrl:ut(e.authBaseUrl),webBaseUrl:ut(e.webBaseUrl),intakeBaseUrl:ut(e.intakeBaseUrl),tailBaseUrl:ut(e.tailBaseUrl),apiDomain:ut(e.apiDomain),webDomain:ut(e.webDomain),intakeDomain:ut(e.intakeDomain),tailDomain:ut(e.tailDomain),forwardPublicKey:ut(e.forwardPublicKey),forwardPublicKeyProjectId:ut(e.forwardPublicKeyProjectId)}),dF=(e)=>({version:2,activeProfile:"default",profiles:{default:Ix(e)}}),pF=(e)=>{let t=ut(e.activeProfile)??"default",n=typeof e.profiles==="object"&&e.profiles!==null?e.profiles:{},r={};for(let[o,i]of Object.entries(n)){if(typeof i!=="object"||i===null)continue;r[o]=Ix(i)}if(!r[t])r[t]={};return{version:2,activeProfile:t,profiles:r}},Oe=()=>{try{if(!Bn.existsSync(ei))return Re(yx);let e=Bn.readFileSync(ei,"utf-8"),t=JSON.parse(e),n=typeof t.version==="number"?t.version:void 0;if(n!==void 0&&n>2)return we("Settings file requires a newer CLI version. Upgrade with 'npm install -g @sazabi/cli@latest'.");if(n===2)return Re(pF(t));let r=dF(t),o=Ne(r);if(!o.success)return o;return Re(r)}catch(e){let t=e instanceof Error?e.message:String(e);return we(t)}},Ne=(e)=>{try{return uF(),Bn.writeFileSync(ei,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),Re(void 0)}catch(t){let n=t instanceof Error?t.message:String(t);return we(n)}},Ht=(e,t)=>{if(t)return t;if(Lb)return Lb;let n=process.env.SAZABI_PROFILE?.trim();if(n)return n;return e.activeProfile??"default"},dt=(e,t)=>{let n=Ht(e,t),r=e.profiles[n];if(r)return Re(r);if(n==="default")return Re({});return we(`Profile '${n}' does not exist. Run 'sazabi profiles create ${n}' first.`)},vt=()=>{let e=Oe();if(!e.success)return e;return dt(e.value)},pt=(e,t,n)=>{let r=Ht(e,n);if(!e.profiles[r])return we(`Profile '${r}' does not exist. Run 'sazabi profiles create ${r}' first.`);return Re({...e,profiles:{...e.profiles,[r]:{...e.profiles[r],...t}}})},Zt=(e)=>{if(!e?.forwardPublicKey&&!e?.forwardPublicKeyProjectId)return{};return{forwardPublicKey:void 0,forwardPublicKeyProjectId:void 0}};var Qe=L(()=>{bx();te();Eb=zb.join(vx.homedir(),".sazabi"),ei=zb.join(Eb,"settings.json")});var Pt=(e)=>{let{cliFlag:t,globalUrl:n,globalDomain:r,buildUrlFromDomain:o,defaultUrl:i}=e;if(t)return t;let a=process.env.SAZABI_API_URL?.trim();if(a)return a;if(n)return n;if(r)return o(r);return i},A=(e)=>{let{tokenFlag:t,organizationIdFlag:n,projectIdFlag:r,jsonMode:o}=e,i=t?.trim(),a=process.env.SAZABI_TOKEN?.trim(),s=process.env.SAZABI_ORGANIZATION_ID?.trim(),c=process.env.SAZABI_PROJECT_ID?.trim(),l=f(vt(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",o),u=l.token?.trim(),d=(i&&i.length>0?i:void 0)||(a&&a.length>0?a:void 0)||u,p=i&&i.length>0?"flag":a&&a.length>0?"environment":"settings";if(hx(p),!d||d.length===0){if(o)return h("You're not signed in. Run 'sazabi auth sign-in' to sign in, or set SAZABI_TOKEN, pass --token, or run 'sazabi auth use-secret-key <secret-key>'.");return g("You're not signed in. Run 'sazabi auth sign-in' to sign in, or set SAZABI_TOKEN, pass --token, or run 'sazabi auth use-secret-key <secret-key>'.")}let m=p==="settings"||d===u,b,y;if(n)b=n,y="flag";else if(s&&s.length>0)b=s,y="environment";else if(m&&l.activeOrganizationId)b=l.activeOrganizationId,y="settings";let I,C;if(r)I=r,C="flag";else if(c&&c.length>0)I=c,C="environment";else if(m&&l.activeProjectId)I=l.activeProjectId,C="settings";return{token:d,type:"token",projectId:I,organizationId:b,tokenSource:p,organizationSource:y,projectSource:C}},Jt=(e)=>{let t=f(vt(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",e?.jsonMode);return Pt({cliFlag:e?.apiBaseUrlFlag,globalUrl:t.apiBaseUrl,globalDomain:t.apiDomain,buildUrlFromDomain:(n)=>`https://api.${n}`,defaultUrl:"https://api.sazabi.com"})},T=(e)=>{let t=e.apiBaseUrl??Jt({apiBaseUrlFlag:e.apiBaseUrlFlag,jsonMode:e.jsonMode});return Fn({token:e.token,baseUrl:t,organizationId:e.organizationId,projectId:e.projectId,sandboxActorDescriptor:process.env.SAZABI_SANDBOX_ACTOR})},kx,Db,Kl=async(e)=>{let t=f(vt(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",e.jsonMode),n=Pt({cliFlag:e.apiBaseUrlFlag,globalUrl:t.apiBaseUrl,globalDomain:t.apiDomain,buildUrlFromDomain:(c)=>`https://api.${c}`,defaultUrl:"https://api.sazabi.com"}),r=`${e.token}@${n}@${e.projectId??""}`,o=kx.get(r);if(o)return o;let i=Db.get(r);if(i)return i;if(!e.projectId){if(e.jsonMode)return h("Project ID is required. Run 'sazabi projects use <project-id>' or set SAZABI_PROJECT_ID.");return g("Project ID is required. Run 'sazabi projects use <project-id>' or set SAZABI_PROJECT_ID.")}let a=e.projectId,s=(async()=>{let l=await Fn({token:e.token,baseUrl:n,projectId:a}).projects.get(a),d=f(l,"Couldn't fetch project info (run 'sazabi projects list' to verify the project ID)",e.jsonMode).project;return kx.set(r,d),d})();Db.set(r,s);try{return await s}finally{Db.delete(r)}},Gl=(e)=>{let t=e.trim().toLowerCase(),n=/^[a-z][a-z0-9+.-]*:\/\//.test(t)?t:`https://${t}`,r=t;try{r=new URL(n).hostname.toLowerCase()}catch{r=t.replace(/^[a-z][a-z0-9+.-]*:\/\//,"").replace(/[/?#].*$/,"").replace(/:\d+$/,"")}return`https://app.${r.replace(/^(?:app\.)+/,"")}`},wx=(e)=>{try{let t=new URL(e),n=t.hostname.toLowerCase();if(!n.startsWith("api."))return null;return`${t.protocol}//app.${n.slice(4)}`}catch{return null}},ti=(e)=>(Boolean(e?.apiBaseUrlFlag?.trim()||process.env.SAZABI_API_URL?.trim())?wx(Jt(e)):null)??on(),on=(e)=>{let t=(r)=>r.replace(/\/+$/,"");if(e)return t(e);let n=f(vt(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)");if(n.webBaseUrl)return t(n.webBaseUrl);if(n.webDomain)return Gl(n.webDomain);if(n.apiDomain)return Gl(n.apiDomain);if(n.apiBaseUrl){let r=wx(n.apiBaseUrl);if(r)return r}return"https://app.sazabi.com"},We=async(e)=>{if(e.projectId&&e.projectId.length>0)return e.projectId;let t=await e.client.me();if(t.success){let r=t.value,o=r.credentialType==="user"?r.authorizedProjectId:r.credentialType==="partner"?void 0:r.projectId;if(o)return o}let n="No project selected. Pass --project-id, set SAZABI_PROJECT_ID, or run 'sazabi projects use <project-id>'.";if(e.jsonMode)return h(n);return g(n)},uo=(e,t)=>`${on(t)}/projects/${e}`,Be=(e,t,n,r)=>{let o=`${on(n)}/projects/${e}/threads/${t}`;return r?`${o}?messageId=${encodeURIComponent(r)}`:o},Cx=(e,t,n,r)=>Be(e,t,n,r),Px=(e,t,n)=>`${uo(e,n)}/issues/${t}`,Ox=(e,t,n)=>`${uo(e,n)}/automations/${t}`,xx=(e,t)=>`${uo(e,t)}/status`,Ax=(e,t,n)=>`${uo(e,n)}/settings/log-source-providers/${t}`,Tx=(e,t,n)=>`${uo(e,n)}/settings/mcp-connectors/${t}`,ql=(e,t,n)=>`${uo(e,n)}/settings/sandbox-clis/catalog/${t}`,_x=(e,t)=>`https://otlp.${t}.intake.${e}`;var se=L(()=>{H();Qr();te();Qe();kx=new Map,Db=new Map});var js,pD=(e)=>{js.set(e.name,e);for(let t of e.aliases??[])js.set(t,e)},ld=(e)=>js.get(e),Rs=()=>Array.from(js.entries()).filter(([e,t])=>e===t.name).map(([,e])=>e),mD=(e)=>js.has(e);var nk=L(()=>{js=new Map});async function sk(e){let t=await e.publicKeys.list({limit:20});if(!t.success)return[];return t.value.publicKeys.map((n)=>({value:n.id,description:n.name}))}async function ck(e){let t=await e.secretKeys.list({limit:20});if(!t.success)return[];return t.value.secretKeys.map((n)=>({value:n.id,description:n.name}))}async function Es(e){let t=await e.logSources.list();if(!t.success)return[];return t.value.logSources.map((n)=>({value:n.id,description:n.name??n.provider}))}async function gD(e){let t=await e.members.list();if(!t.success)return[];return t.value.members.map((n)=>({value:n.userId,description:n.name??n.email}))}var K5=3000,q5,hD=async(e,t,n)=>{try{let r=q5[e]?.[t];if(!r)return[];let o=vt();if(!o.success)return[];let i=o.value,a=process.env.SAZABI_TOKEN?.trim()||i.token?.trim();if(!a)return[];let s=Pt({globalUrl:i.apiBaseUrl,globalDomain:i.apiDomain,buildUrlFromDomain:(u)=>`https://api.${u}`,defaultUrl:"https://api.sazabi.com"}),c=Fn({token:a,baseUrl:s,organizationId:i.activeOrganizationId,projectId:i.activeProjectId});return(await Promise.race([r(c),new Promise((u)=>setTimeout(()=>u([]),K5))])).filter((u)=>u.value.startsWith(n))}catch{return[]}};var fD=L(()=>{Qr();se();Qe();q5={threads:{get:async(e)=>{let t=await e.threads.list({limit:20});if(!t.success)return[];return t.value.threads.map((n)=>({value:n.id,description:n.title??void 0}))}},projects:{use:async(e)=>{let t=await e.projects.list();if(!t.success)return[];return t.value.projects.map((n)=>({value:n.id,description:n.name}))}},organizations:{use:async(e)=>{let t=await e.organizations.list();if(!t.success)return[];return t.value.organizations.map((n)=>({value:n.id,description:n.name}))},rename:async(e)=>{let t=await e.organizations.list();if(!t.success)return[];return t.value.organizations.map((n)=>({value:n.id,description:n.name}))}},"public-keys":{get:sk,update:sk,deactivate:sk},"secret-keys":{get:ck,update:ck,delete:ck},"log-sources":{get:Es,enable:Es,disable:Es,delete:Es,remove:Es},members:{"update-role":gD,remove:gD}}});var bD={};hn(bD,{getCompletions:()=>Z5,parseCompletionContext:()=>H5});var W5,V5,H5=(e)=>{let t=e.length>0?e:[""],n=t.length-1,r=t[n]??"";return{words:t,currentIndex:n,partial:r}},Z5=async(e)=>{let{words:t,currentIndex:n,partial:r}=e,o=t[n-1];if(o==="--profile")return X5(r);let i=Y5(t),a=Math.max(0,i.length-(t.length-n));if(a===0)return J5(r);let s=i[0]??"",c=ld(s);if(!c)return[];if(a===1&&c.subcommands){if(r.startsWith("-"))return lk(c.options,i);return yD(c,r)}let l=c.subcommands?i[1]:void 0,u=l?c.subcommands?.[l]:void 0;if(a===2&&u?.subcommands){if(r.startsWith("-"))return lk(u.options,i);return yD(u,r)}let d=u?.subcommands?i[2]:void 0,p=d?u?.subcommands?.[d]:void 0,m=p?.options??u?.options??c.options;if(r.startsWith("-"))return lk(m,i);if(o?.startsWith("--")){let b=o.slice(2);if(m?.[b]?.type==="string"){let I=p?`${s}:${l??""}:${d??""}`:`${s}:${l??""}`,C=V5[I]?.[b]??W5[b];if(C)return C.filter((B)=>B.startsWith(r)).map((B)=>({value:B}));return[]}}return hD(s,l??"",r)},J5=(e)=>{let n=Rs().filter((o)=>o.name.startsWith(e)).map((o)=>({value:o.name,description:o.description})),r=[{value:"--help",description:"Show help"},{value:"--version",description:"Show version"},{value:"--profile",description:"Use a named profile"}];for(let o of r)if(o.value.startsWith(e))n.push(o);return n},yD=(e,t)=>{if(!e.subcommands)return[];return Object.values(e.subcommands).filter((n)=>n.name.startsWith(t)).map((n)=>({value:n.name,description:n.description}))},lk=(e,t)=>{let n=t[t.length-1]??"",r=new Set(t.filter((i)=>i.startsWith("--")).map((i)=>i.replace(/=.*/,""))),o=[];if(!r.has("--help")&&"--help".startsWith(n))o.push({value:"--help",description:"Show help"});if(!r.has("--profile")&&"--profile".startsWith(n))o.push({value:"--profile",description:"Use a named profile"});if(!e)return o;for(let[i,a]of Object.entries(e)){let s=`--${i}`;if(r.has(s))continue;if(!s.startsWith(n))continue;o.push({value:s,description:a.description})}return o},Y5=(e)=>{let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r==="--profile"&&n+1<e.length)n++;else if(r.startsWith("--profile="));else t.push(r)}return t},X5=(e)=>{try{let t=Oe();if(!t.success)return[];return Object.keys(t.value.profiles).filter((n)=>n.startsWith(e)).map((n)=>({value:n,description:n===t.value.activeProfile?"active":void 0}))}catch{return[]}};var vD=L(()=>{nk();Qe();fD();W5={status:["regular","archived"],format:["json","text"]},V5={"members:update-role":{role:["admin","member"]},"messages:search":{role:["user","assistant"]},"messages:list":{role:["user","assistant"]},"setup-tasks:list":{status:["done","not-done","skipped"]}}});H();H();H();import{parseArgs as Ak}from"node:util";var HD=(e)=>{let t=new Map;for(let[n,r]of Object.entries(e)){if(!r.negatable)continue;let o=`no-${n}`;if(r.type!=="boolean"||Object.hasOwn(e,o))throw Error(`Flag --${n} cannot be negatable: ${r.type!=="boolean"?"only boolean flags negate":`--${o} is already declared`}.`);t.set(o,n)}return t},ZD=(e,t)=>{let n={};for(let[r,{negatable:o,...i}]of Object.entries(e))n[r]=i;for(let r of t.keys())n[r]={type:"boolean"};return n},S=(e,t,n={})=>{let r=HD(t),o=ZD(t,r),i=Object.hasOwn(t,"json")&&e.includes("--json"),a=(m,b)=>{if(i)h({code:m,message:b,operationId:null});throw g(b),Error("Unreachable")},s=(()=>{try{return Ak({args:e,options:o,allowPositionals:Boolean(n.allowPositionals),strict:!1,tokens:!0})}catch(m){let b=new Set(Object.keys(o)),y=new Set(Object.values(o).map((C)=>C.short).filter((C)=>Boolean(C)));try{let C=Ak({args:e,options:o,allowPositionals:!0,strict:!1,tokens:!0}),B=[...new Set((C.tokens??[]).flatMap((V)=>V.kind==="option"?[V]:[]).filter((V)=>!b.has(V.name)&&!(V.name.length===1&&y.has(V.name))).map((V)=>V.name.length>1?`--${V.name}`:`-${V.name}`))];if(B.length>0)return a("UNEXPECTED_ARGUMENT",`Unknown option${B.length>1?"s":""}: ${B.join(", ")}. Run the command with -h for usage.`)}catch{}let I=m instanceof Error?m.message:"Invalid arguments.";return a("INVALID_ARGUMENT",`${I.endsWith(".")?I:`${I}.`} Run the command with -h for usage.`)}})(),c=Object.hasOwn(t,"json")&&s.values.json===!0,l=new Set(Object.keys(o)),u=new Set(Object.entries(o).map(([,m])=>m.short).filter((m)=>Boolean(m))),d=[];if(Array.isArray(s.tokens))for(let m of s.tokens){if(m.kind!=="option")continue;let b=m.name,y=b.length>1;if(!(l.has(b)||!y&&u.has(b))){let C=y?`--${b}`:`-${b}`;if(!d.includes(C))d.push(C)}}for(let m of Object.keys(s.values))if(!l.has(m)){let b=m.length>1?`--${m}`:`-${m}`;if(!d.includes(b))d.push(b)}if(d.length>0){let m=`Unknown option${d.length>1?"s":""}: ${d.join(", ")}. Run the command with -h for usage.`;if(c)h({code:"UNEXPECTED_ARGUMENT",message:m,operationId:null});g(m)}for(let[m,b]of Object.entries(t))if(b.type==="string"&&s.values[m]===!0){let y=m.length===1?`-${m}`:`--${m}`,I=`Option ${y} requires a value. Use '${y} <value>'.`;a("INVALID_ARGUMENT",I)}for(let[m,b]of Object.entries(t)){let y=s.values[m];if(b.type==="string"&&typeof y==="string"){if(y.length===0){let C=m.length===1?`-${m}`:`--${m}`;a("INVALID_ARGUMENT",`Option ${C} requires a non-empty value.`)}if(y.startsWith("--")||y.length===2&&y[0]==="-"&&/[a-zA-Z]/.test(y.charAt(1))){let B=`Option ${m.length===1?`-${m}`:`--${m}`} received "${y}" as its value. Did you forget to provide a value?`;a("INVALID_ARGUMENT",B)}}}if(!n.allowPositionals&&s.positionals.length>0)a("UNEXPECTED_ARGUMENT",`Unexpected argument${s.positionals.length>1?"s":""}: ${s.positionals.join(", ")}. Run the command with -h for usage.`);let p=s.values;for(let[m,b]of r){let y=p[m];if(delete p[m],y===void 0)continue;if(y!==!0)a("INVALID_ARGUMENT",`Option --${m} does not take a value.`);if(p[b]!==void 0)a("INVALID_ARGUMENT",`Use either --${b} or --${m}, not both.`);p[b]=!1}return{values:p,positionals:s.positionals}};var O={token:{type:"string"},"api-base-url":{type:"string"},json:{type:"boolean"}},x={token:{type:"string",description:"Override token"},"api-base-url":{type:"string",description:"Override API base URL"},json:{type:"boolean",description:"Output as JSON"}};se();var Wl=(e,t)=>{if(e?.json?.type!=="boolean")throw Error(`${t} must include a boolean --json option (enforced by CommandBuilder)`)};class jx{name;description;handler;subcommands;options;examples;details;positionalArgs;allowNoJson=!1;constructor(e,t,n){this.name=e,this.description=t,this.handler=n}withDetails(e){return this.details=e,this}withOptions(e){return this.options=e,this}withSubcommands(e){return this.subcommands=e,this}withExamples(e){return this.examples=e,this}withPositionalArgs(e){return this.positionalArgs=e,this}build(){if(!this.handler&&!this.subcommands)throw Error(`Subcommand "${this.name}" must have either a handler or subcommands`);if(this.handler&&this.subcommands)throw Error(`Subcommand "${this.name}" must have either a handler or subcommands, not both`);if(!this.allowNoJson&&this.handler)Wl(this.options,`Subcommand "${this.name}"`);if(!this.allowNoJson&&this.subcommands){for(let[e,t]of Object.entries(this.subcommands))if(!t.subcommands)Wl(t.options,`Subcommand "${this.name} ${e}"`)}return{name:this.name,description:this.description,handler:this.handler,subcommands:this.subcommands,options:this.options,examples:this.examples,details:this.details,positionalArgs:this.positionalArgs}}allowWithoutJson(){return this.allowNoJson=!0,this}}class Rx{name;aliases;description;handler;subcommands;options;examples;positionalArgs;allowNoJson=!1;constructor(e,t){this.name=e,this.description=t}withAliases(e){return this.aliases=e,this}withHandler(e){return this.handler=e,this}withSubcommands(e){return this.subcommands=e,this}withOptions(e){return this.options=e,this}withExamples(e){return this.examples=e,this}withPositionalArgs(e){return this.positionalArgs=e,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)Wl(this.options,`Command "${this.name}"`);if(this.subcommands)for(let[e,t]of Object.entries(this.subcommands)){if(t.subcommands)continue;Wl(t.options,`Subcommand "${this.name} ${e}"`)}}return{name:this.name,aliases:this.aliases,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 q=(e,t)=>new Rx(e,t),v=(e,t,n)=>new jx(e,t,n);te();H();var et=(e,t,n,r,o)=>{let i=Number.parseInt(e,10);if(Number.isNaN(i)||i<t||i>n){let a=`${r} must be between ${t} and ${n}.`;if(o)return h(a);return g(a)}return i},po=(e,t,n,r)=>{if(!t.includes(e)){let o=t.map((a)=>`"${a}"`).join(" or "),i=`${n} must be ${o}.`;if(r)return h(i);return g(i)}return e};H();se();te();var Nb=(e)=>{let t=[];for(let n of e){let r=0;for(let o of n.content){if(o.type!=="artifact")continue;t.push({id:`${n.id}:${r}`,messageId:n.id,name:o.name,toolCallId:o.toolCallId??null,createdAt:n.createdAt,data:o.data}),r+=1}}return t},Ex=(e)=>{let t=e.lastIndexOf(":");if(t<=0||t===e.length-1)return null;let n=e.slice(0,t),r=e.slice(t+1);if(!/^\d+$/.test(r))return null;return{messageId:n,index:Number.parseInt(r,10)}},Lx=(e,t)=>Nb(e).find((n)=>n.id===t),$b=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),Vl=(e)=>{let t=e===null||e===void 0?"":typeof e==="object"?JSON.stringify(e):String(e);if(/[",\n\r]/.test(t))return`"${t.replace(/"/g,'""')}"`;return t},mF=(e)=>{if(Array.isArray(e)&&e.every($b))return e;if($b(e))for(let t of["rows","data","items","points"]){let n=e[t];if(Array.isArray(n)&&n.every($b))return n}return null},zx=(e)=>{let t=mF(e);if(!t||t.length===0)return null;let n=[];for(let o of t)for(let i of Object.keys(o))if(!n.includes(i))n.push(i);if(n.length===0)return null;let r=[n.map(Vl).join(",")];for(let o of t)r.push(n.map((i)=>Vl(o[i])).join(","));return r.join(`
|
|
118
118
|
`)};var gF=100,Dx=100,hF=async(e,t,n)=>{let r=[],o;for(let i=0;i<Dx;i++){let a=await e.messages.list(t,{limit:gF,...o?{cursor:o}:{}}),s=f(a,"Couldn't get artifact (check the thread ID and try again)",n);if(r.push(...s.messages),!s.nextCursor)break;o=s.nextCursor}if(o&&!n)console.error(`Warning: reached the ${Dx}-page limit; the artifact may exist beyond the scanned messages.`);return r},fF=(e,t,n)=>{if(t)return t;let r=`--thread-id is required to locate artifact '${e}'. Usage: sazabi artifacts get <artifact-id> --thread-id <thread-id>`;if(n)h(r);else g(r);return},yF=(e,t)=>{if(t.json){j({id:e.id,messageId:e.messageId,name:e.name,toolCallId:e.toolCallId,createdAt:e.createdAt,data:e.data});return}if(t.format==="csv"){let n=zx(e.data);if(n===null){g(`Artifact '${e.id}' (${e.name}) has no embedded rows to render as CSV. Built-in table/timeseries artifacts persist query parameters rather than result rows, so only artifacts that embed their data (such as custom artifacts) can be exported as CSV. Use --json or the default output to inspect this artifact.`);return}console.log(n);return}console.log(JSON.stringify(e.data,null,2))},$x=async(e,t)=>{if(!Ex(e)){let c=`Invalid artifact ID: '${e}'. Expected format '<message-id>:<index>' (from 'sazabi artifacts list').`;if(t.json)return h(c);return g(c)}let r=fF(e,t.threadId,t.json);if(!r)return;let o=A({tokenFlag:t.token,jsonMode:t.json}),i=T({token:o.token,projectId:o.projectId,apiBaseUrlFlag:t.apiBaseUrl}),a=await hF(i,r,t.json),s=Lx(a,e);if(!s){let c=`Artifact '${e}' not found in thread '${r}'. Run 'sazabi artifacts list --thread-id ${r}' to see available artifacts.`;if(t.json)return h(c);return g(c)}yF(s,t)};H();se();te();var bF={id:{label:"ID",type:{kind:"string"}},name:{label:"Type",type:{kind:"string"}},toolCallId:{label:"Tool call",type:{kind:"nullable-string",emptyLabel:"(none)"}},createdAt:{label:"Created",type:{kind:"date"}}},vF={schema:bF,columns:["id","name","toolCallId","createdAt"],header:"Artifacts",emptyMessage:"No artifacts found in this thread."},SF=100,Nx=100,IF=async(e,t,n)=>{let r=[],o;for(let i=0;i<Nx;i++){let a=await e.messages.list(t,{limit:SF,...o?{cursor:o}:{}}),s=f(a,"Couldn't list artifacts (check the thread ID and try again)",n);if(r.push(...s.messages),!s.nextCursor)break;o=s.nextCursor}if(o&&!n)console.error(`Warning: reached the ${Nx}-page limit; artifact list may be incomplete for this thread.`);return r},Ux=async(e)=>{let t=A({tokenFlag:e.token,jsonMode:e.json}),n=T({token:t.token,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl}),r=await IF(n,e.threadId,e.json),i=Nb(r).map((a)=>({id:a.id,name:a.name,toolCallId:a.toolCallId,createdAt:a.createdAt}));D(vF,i,{json:e.json})};var Mx={id:{label:"ID",type:{kind:"string"}},issueId:{label:"Issue ID",type:{kind:"nullable-string"}},type:{label:"Type",type:{kind:"string"}},title:{label:"Title",type:{kind:"string"}},url:{label:"URL",type:{kind:"string"}},contentType:{label:"Content type",type:{kind:"nullable-string"}},sizeBytes:{label:"Size (bytes)",type:{kind:"custom",render:(e)=>e==null?"":String(e),serialize:(e)=>e??null}},createdAt:{label:"Created",type:{kind:"date"}}},kF={layout:"field-list",schema:Mx,fields:["id","issueId","type","title","url","contentType","sizeBytes","createdAt"],title:"Artifact"},wF={schema:Mx,columns:["id","issueId","type","title","createdAt"],jsonFields:["id","issueId","type","title","url","contentType","sizeBytes","createdAt"],header:"Artifacts",emptyMessage:"No artifacts found."},Zl=(e)=>{let t=A({tokenFlag:e.token,projectIdFlag:e.projectId,jsonMode:e.json});return T({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:e.json})},CF=async(e)=>{let{values:t,positionals:n}=S(e,{...O,"project-id":{type:"string"},"issue-id":{type:"string"},"thread-id":{type:"string"},type:{type:"string"},"created-after":{type:"string"},"created-before":{type:"string"},limit:{type:"string"},cursor:{type:"string"}},{allowPositionals:!0}),r=t["thread-id"];if(r){if(n.length>0)return t.json?h("The legacy --thread-id form does not accept an issue ID."):g("The legacy --thread-id form does not accept an issue ID.");await Ux({threadId:r,token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]});return}if(n.length>1||n[0]&&t["issue-id"])return t.json?h("Provide an issue ID either positionally or with --issue-id, not both."):g("Provide an issue ID either positionally or with --issue-id, not both.");let o=t["issue-id"]??n[0],i=t["project-id"],a=Zl({token:t.token,projectId:i,json:t.json,apiBaseUrl:t["api-base-url"]}),s=f(await a.artifacts.list({projectId:i,issueId:o,type:t.type,createdAfter:t["created-after"],createdBefore:t["created-before"],limit:t.limit?Number(t.limit):void 0,cursor:t.cursor}),"Couldn't list artifacts",t.json);D(wF,s.artifacts,{json:t.json,nextCursor:s.nextCursor})},PF=async(e)=>{let{values:t,positionals:n}=S(e,{...O,"project-id":{type:"string"},"thread-id":{type:"string"},format:{type:"string"}},{allowPositionals:!0}),r=n[0];if(!r)return t.json?h("Artifact ID is required."):g("Artifact ID is required.");if(t["thread-id"]){if(n.length>1){let c=`Unexpected arguments: ${n.slice(1).join(", ")}.`;return t.json?h(c):g(c)}let a=t.format?po(t.format,["json","csv"],"Format",t.json):void 0;await $x(r,{threadId:t["thread-id"],token:t.token,format:a,json:t.json,apiBaseUrl:t["api-base-url"]});return}let o=Zl({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]}),i=f(await o.artifacts.get({artifactId:r,projectId:t["project-id"]}),`Couldn't get artifact ${r}`,t.json);R(kF,i,{json:t.json})},OF=async(e)=>{let{values:t,positionals:n}=S(e,{...O,"project-id":{type:"string"}},{allowPositionals:!0}),r=n[0];if(!r)return t.json?h("Artifact ID is required."):g("Artifact ID is required.");let o=Zl({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]}),i=f(await o.artifacts.download({artifactId:r,projectId:t["project-id"]}),`Couldn't create a download URL for artifact ${r}`,t.json);if(t.json)j(i);else z(i.url)},xF=async(e)=>{let{values:t,positionals:n}=S(e,{...O,"project-id":{type:"string"}},{allowPositionals:!0}),r=n[0];if(!r)return t.json?h("Artifact ID is required."):g("Artifact ID is required.");let o=Zl({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]});if(f(await o.artifacts.delete({artifactId:r,projectId:t["project-id"]}),`Couldn't delete artifact ${r}`,t.json),t.json)j({artifactId:r,deleted:!0});else z(`Artifact ${r} deleted.`)},AF={...x,"project-id":{type:"string",description:"Override active project ID"},"thread-id":{type:"string",description:"Legacy thread to list or fetch embedded artifacts"},format:{type:"string",description:"Legacy artifact output format: json or csv"}},Hl=(e,t,n,r)=>{let o=v(e,t,n).withOptions(AF);return r?o.withPositionalArgs(r).build():o.build()},Fx=q("artifacts","Manage issue artifacts").withSubcommands({list:Hl("list","List project artifacts or legacy thread artifacts",CF,"[issue-id]"),get:Hl("get","Get artifact details or legacy thread artifact data",PF,"<artifact-id>"),download:Hl("download","Create a short-lived artifact download URL",OF,"<artifact-id>"),delete:Hl("delete","Delete an artifact",xF,"<artifact-id>")}).withExamples(["sazabi artifacts list --project-id <project-id> # List project artifacts","sazabi artifacts list --thread-id <thread-id> # List legacy thread artifacts","sazabi artifacts download <artifact-id> # Create a download URL"]).build();H();jb();se();import{spawn as TF}from"node:child_process";var tt=(e)=>{let t=process.platform,n,r;if(t==="darwin")n="open",r=[e];else if(t==="win32")n="cmd",r=["/c","start","",e];else n="xdg-open",r=[e];let o=TF(n,r,{detached:!0,stdio:"ignore"});o.on("error",()=>{}),o.unref()},$t=(e)=>new Promise((t)=>setTimeout(t,e));import{createInterface as Xx}from"node:readline";H();import{createInterface as _F}from"node:readline";var Bb=(e)=>!e.action&&!e.excludedFromSelectAll,qx=(e)=>e.action===!0&&!e.selectAll,Cn="Back",mo="Quit",ni=Symbol("prompt-back"),Ql=()=>({label:Cn,value:ni,action:!0}),oi=Symbol("prompt-quit"),eu=()=>({label:mo,value:oi,action:!0}),jF=Symbol("prompt-select-all"),RF=()=>({label:"Select all",value:jF,action:!0,selectAll:!0}),Yl=null,Gb=(e)=>{Yl=e},Va=()=>Yl,EF="\x03",Bx="\x1B[A",LF="\x1B[B",Jl="\x1B[2K",Xl=(e)=>e>0?`\x1B[${e}A`:"",Gn=String.fromCharCode(27),Kb=String.fromCharCode(127),zF=String.fromCharCode(8),DF=100,Gx=(e)=>e<" "||e===Kb,$F=(e)=>{let t=[],n=0;while(n<e.length){let r=e[n];if(r===Gn){if(n+1>=e.length)return{tokens:t,pending:Gn};let i=e[n+1];if(i==="["||i==="O"){let a=n+2;while(i==="["&&a<e.length&&e[a]>=" "&&e[a]<="?")a+=1;if(a>=e.length)return{tokens:t,pending:e.slice(n)};t.push(e.slice(n,a+1)),n=a+1;continue}t.push(e.slice(n,n+2)),n+=2;continue}if(Gx(r)){t.push(r),n+=1;continue}let o=n+1;while(o<e.length&&!Gx(e[o])&&e[o]!==Gn)o+=1;t.push(e.slice(n,o)),n=o}return{tokens:t,pending:""}},NF=new RegExp(`${Gn}\\[[0-9;]*[0-9A-Za-z]`,"g"),UF=new RegExp(`^${Gn}\\[[0-9;]*[0-9A-Za-z]`),MF=`${Gn}[0m`,FF="…",BF=(e)=>e.replace(NF,"").length,GF=(e,t)=>{if(t<=1||BF(e)<=t)return e;let n="",r=0,o=0,i=t-1;while(o<e.length&&r<i){if(e[o]===Gn){let a=UF.exec(e.slice(o));if(a){n+=a[0],o+=a[0].length;continue}}n+=e[o],r+=1,o+=1}return`${n}${FF}${MF}`},KF=(e)=>e.length>0&&[...e].every((t)=>t>=" "&&t!==Kb),Wx=(e)=>{let{output:t,message:n,answer:r,choiceCount:o}=e,i=o+1;t.write(Xl(i));for(let a=0;a<i;a+=1)t.write(`${Jl}
|
|
119
119
|
`);if(t.write(Xl(i)),e.echoAnswer===!1)return;t.write(`${_.muted("?")} ${_.bold(n)} ${_.muted(r)}
|
|
@@ -223,7 +223,7 @@ ${mK(n)}`:"";if(!e){let i=`--credentials is required for ${t} (JSON object).${o}
|
|
|
223
223
|
Waiting for the run to finish ${Wb}`);let s=()=>xW(e.printProgress,r||a);try{while(!0){let c=await e.client.runs.get(e.runId);if(!c.success){if(!AW(c))return s(),c}else if(o=c.value,c.value.completed)return s(),c;if(e.timeoutMs!==void 0&&Date.now()-n>=e.timeoutMs)return s(),Re(o);if(r=OW(e.printProgress,r),await(i.cancellation?i.cancellation.wait(t):ss(t)),i.cancellation?.requested())return s(),i.endIfStandalone(`Cancelled. The run is still processing; check it with 'sazabi runs get ${e.runId}'.`),Re(o)}}finally{i.dispose()}},OW=(e,t)=>{if(!e)return t;if(!t)process.stdout.write(`
|
|
224
224
|
`);return process.stdout.write("."),!0},xW=(e,t)=>{if(!e||!t)return;process.stdout.write(`
|
|
225
225
|
`)},AW=(e)=>e.statusCode===404;var TW={threadId:{label:"Thread ID",type:{kind:"id"}},messageId:{label:"Message ID",type:{kind:"nullable-string",emptyLabel:"(pending)"}},url:{label:"URL",type:{kind:"nullable-string"},get:(e)=>e.threadUrl??null},runId:{label:"Run ID",type:{kind:"id"}},status:{label:"Status",type:{kind:"string"}},pollWith:{label:"Poll with",type:{kind:"string"},get:(e)=>`sazabi runs get ${e.runId}`},response:{label:"Response",type:{kind:"nullable-string"},get:(e)=>e.response}},_W={layout:"sections",schema:TW,primary:{title:"Thread",fields:["threadId","messageId","url","runId","status","pollWith"]},secondary:[{title:"Response",field:"response"}]},X_=()=>process.env.SAZABI_AUTOMATION_ID??process.env.SAZABI_SCRIPT_PARAM_AUTOMATION_ID,Q_=()=>process.env.SAZABI_AMBIENT_SERVICE_RUN==="true"?!0:void 0,jW=async(e)=>{let t=Date.now(),n=e.waitTimeoutSeconds===void 0?void 0:e.waitTimeoutSeconds*1000,r=await nj({message:e.message,threadId:e.threadId,projectId:e.projectId,json:e.json,client:e.client,wait:!0,timeoutMs:n,automationId:e.automationId,ambientServiceRun:e.ambientServiceRun});if(r.status==="processing"){let o=n===void 0?void 0:Math.max(0,n-(Date.now()-t)),i=f(await Tu({client:e.client,runId:r.runId,threadId:r.threadId,timeoutMs:o,printProgress:!e.json}),`Couldn't get run (poll again with 'sazabi runs get ${r.runId}')`,e.json);r={...r,status:i.status,response:i.response,messageId:r.messageId??i.messageId}}return r},tj=async(e,t={})=>{let n=A({tokenFlag:t.token,jsonMode:t.json}),r=T({token:n.token,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl}),o=t.wait?await jW({client:r,message:e,threadId:t.threadId,projectId:n.projectId,waitTimeoutSeconds:t.timeout===void 0?void 0:t.timeout/1000,json:t.json,automationId:X_(),ambientServiceRun:Q_()}):await nj({message:e,threadId:t.threadId,projectId:n.projectId,json:t.json,client:r,wait:!1,timeoutMs:t.timeout,automationId:X_(),ambientServiceRun:Q_()}),{threadUrl:i,...a}=o;R(_W,o,{json:t.json,contract:a})},nj=async(e)=>{if(e.threadId){let n=f(await e.client.messages.append(e.threadId,e.message,e.wait??!1,ej(e.timeoutMs),e.automationId,e.ambientServiceRun),"Failed to send message",e.json);return{threadId:e.threadId,runId:n.result.runId,messageId:n.result.messageId,status:n.result.status,response:n.result.response,threadUrl:e.projectId?Be(e.projectId,e.threadId,void 0,n.result.messageId):void 0}}let t=f(await e.client.threads.create({message:e.message,...e.projectId?{projectId:e.projectId}:{},wait:e.wait??!1,timeoutSeconds:ej(e.timeoutMs),...e.automationId!==void 0?{automationId:e.automationId}:{},...e.ambientServiceRun?{ambientServiceRun:!0}:{}}),"Failed to create thread",e.json);return{threadId:t.result.threadId,runId:t.result.runId,messageId:t.result.messageId,status:t.result.status,response:t.result.response,threadUrl:e.projectId?Be(e.projectId,t.result.threadId,void 0,t.result.messageId):void 0}},ej=(e)=>{if(e===void 0)return 20;return Math.max(1,Math.min(Math.ceil(e/1000),20))};var RW={id:{label:"ID",type:{kind:"string"}},role:{label:"Role",type:{kind:"role"}},content:{label:"Content",type:{kind:"custom",render:(e)=>{let n=e.find((r)=>r.type==="message"&&Boolean(r.message));return n?fn(n.message):Je("(no text)")}}},createdAt:{label:"Created",type:{kind:"date"}}},EW={schema:RW,columns:["id","role","content","createdAt"],header:"Messages",emptyMessage:"No messages found."},LW={id:{label:"ID",type:{kind:"string"}},threadTitle:{label:"Thread",type:{kind:"nullable-string",emptyLabel:"(no title)"}},role:{label:"Role",type:{kind:"role"}},content:{label:"Content",type:{kind:"custom",render:(e)=>fn(e)}},score:{label:"Score",align:"right",type:{kind:"custom",render:(e)=>e!=null?e.toFixed(2):"-"}}},zW={schema:LW,columns:["id","threadTitle","role","content","score"],header:{title:"Search results",variant:"search"},emptyMessage:"No matching messages found."},DW=async(e,t)=>{let n=A({tokenFlag:t.token,jsonMode:t.json}),r=T({token:n.token,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl}),{messages:o,nextCursor:i}=f(await r.messages.list(e,{limit:t.limit,cursor:t.cursor}),"Couldn't list messages (check the thread ID and try again)",t.json);D(EW,o,{json:t.json,nextCursor:i})},$W=async(e,t)=>{let n=A({tokenFlag:t.token,jsonMode:t.json}),r=T({token:n.token,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl}),{messages:o,pagination:i}=f(await r.search.messages({query:e,limit:t.limit,page:t.page,threadId:t.threadId,role:t.role}),"Couldn't search messages (check the active project and try again)",t.json);if(t.json){j({messages:o,pagination:i});return}D(zW,o,{count:i.totalResults}),Ao({type:"page",page:i.page,totalPages:i.totalPages})},oj=q("messages","Send, list, and search messages").withSubcommands({send:v("send","Send a message (creates new thread if --thread-id omitted)",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},"thread-id":{type:"string",short:"t"},wait:{type:"boolean"},timeout:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),r=n.join(" ");if(!r){if(t.json)return h("Message is required. Usage: sazabi messages send <message> [--thread-id <id>]");return g("Message is required. Usage: sazabi messages send <message> [--thread-id <id>]")}let o=t.timeout?et(t.timeout,1,3600,"Timeout",t.json)*1000:void 0,i={token:t.token,threadId:t["thread-id"],wait:t.wait,timeout:o,json:t.json,apiBaseUrl:t["api-base-url"]};await tj(r,i)}).withPositionalArgs("<message>").withOptions({token:{type:"string",description:"Override token"},"thread-id":{type:"string",short:"t",description:"Thread ID to append to (creates new thread if omitted)"},wait:{type:"boolean",description:"Wait for assistant response and print it"},timeout:{type:"string",description:"Timeout in seconds to wait for response before returning processing state"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi messages send 'Hello' # Start a new thread","sazabi messages send 'Hello' --thread-id abc123 # Append to existing thread","sazabi messages send 'Hello' -t abc123 --wait # Append and wait for reply","sazabi messages send 'Hello' --wait # New thread, wait for reply","sazabi messages send 'Hello' --wait --timeout 120 # Wait up to 2 minutes"]).build(),list:v("list","List messages in a thread",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},limit:{type:"string"},cursor:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Thread ID is required. Usage: sazabi messages list <thread-id>");return g("Thread ID is required. Usage: sazabi messages list <thread-id>")}if(n.length>1){let i=n.slice(1).join(", ");if(t.json)return h(`Unexpected arguments: ${i}. Run 'sazabi messages -h' for usage.`);return g(`Unexpected arguments: ${i}. Run 'sazabi messages -h' for usage.`)}let o={token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]};if(t.limit)o.limit=et(t.limit,1,100,"Limit",t.json);if(t.cursor)o.cursor=t.cursor;await DW(r,o)}).withPositionalArgs("<thread-id>").withOptions({token:{type:"string",description:"Override token"},limit:{type:"string",description:"Maximum number of messages to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from previous response"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi messages list <thread-id> # List all messages in thread","sazabi messages list <thread-id> --limit 20 # List with custom limit","sazabi messages list <thread-id> --cursor xyz # List next page"]).build(),search:v("search","Search messages in the active project",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},limit:{type:"string"},page:{type:"string"},"thread-id":{type:"string"},role:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),r=n.join(" ");if(!r){if(t.json)return h("Search query is required. Usage: sazabi messages search <query>");return g("Search query is required. Usage: sazabi messages search <query>")}let o={token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]};if(t.limit)o.limit=et(t.limit,1,100,"Limit",t.json);if(t.page)o.page=et(t.page,1,Number.MAX_SAFE_INTEGER,"Page",t.json);if(t["thread-id"])o.threadId=t["thread-id"];if(t.role)o.role=po(t.role,["user","assistant"],"Role",t.json);await $W(r,o)}).withPositionalArgs("<query>").withOptions({token:{type:"string",description:"Override token"},limit:{type:"string",description:"Maximum number of results (default: 20, max: 100)"},page:{type:"string",description:"Page number for pagination (default: 1)"},"thread-id":{type:"string",description:"Filter messages by thread ID"},role:{type:"string",description:"Filter by role: user or assistant"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(['sazabi messages search "error handling" # Search messages','sazabi messages search "bug" --limit 50 # Search with limit','sazabi messages search "user input" --role user # Search user messages only','sazabi messages search "response" --thread-id thread-123 # Search in specific thread']).build()}).withExamples(["sazabi messages send 'Hello' # Start a new thread","sazabi messages send 'Follow up' -t <thread-id> # Append to thread","sazabi messages list <thread-id> # List messages in thread",'sazabi messages search "error" # Search messages']).build();H();se();te();var Zv=["low","medium","high","critical"],ij={id:{label:"ID",type:{kind:"string"}},notificationTypes:{label:"Events",type:{kind:"string"}},destinations:{label:"Destinations",type:{kind:"string"}},severities:{label:"Severities",type:{kind:"nullable-string"}},components:{label:"Components",type:{kind:"nullable-string"}},includeDescendants:{label:"Include descendants",type:{kind:"boolean"}},createdAt:{label:"Created",type:{kind:"date"}}},NW={schema:ij,columns:["id","notificationTypes","destinations","severities","createdAt"],header:"Notification delivery rules",emptyMessage:"No delivery rules. Create one with 'sazabi notifications delivery-rules create'."},aj={layout:"field-list",schema:ij,fields:["id","notificationTypes","destinations","severities","components","includeDescendants","createdAt"],title:"Notification delivery rule"},Jv=(e)=>({id:e.id,notificationTypes:e.notificationTypes.join(", "),destinations:e.destinations.map((t)=>t.displayName||`${t.channel}:${t.destinationKey}`).join(", "),severities:e.condition.severities?.join(", ")??null,components:e.components.length>0?e.components.map((t)=>t.label).join(", "):null,includeDescendants:e.includeDescendants,createdAt:e.createdAt}),bi={...O,"project-id":{type:"string"}},yi={...x,"project-id":{type:"string",description:"Override active project ID"}},vi=(e)=>{let t=e.json,n=A({tokenFlag:e.token,projectIdFlag:e["project-id"],jsonMode:t});return{client:T({token:n.token,organizationId:n.organizationId,projectId:n.projectId,apiBaseUrlFlag:e["api-base-url"],jsonMode:t}),json:t}},_u=(e)=>{if(Array.isArray(e))return e.filter((t)=>typeof t==="string");return typeof e==="string"?[e]:[]},UW=(e,t)=>{let n=[];for(let r of e){let o=r.indexOf(":");if(o<=0||o===r.length-1){let i=`Invalid --destination "${r}". Use channel:key (see 'sazabi notifications delivery-rules options').`;if(t)h(i);else g(i);return null}n.push({channel:r.slice(0,o),destinationKey:r.slice(o+1)})}return n},MW=(e,t)=>{for(let n of e)if(!Zv.includes(n)){let r=`Invalid --severity "${n}". Allowed: ${Zv.join(", ")}.`;if(t)h(r);else g(r);return null}return e},sj={"notification-type":{type:"string",multiple:!0},destination:{type:"string",multiple:!0},"component-id":{type:"string",multiple:!0},"include-descendants":{type:"boolean"},severity:{type:"string",multiple:!0}},rj={"notification-type":{type:"string",description:"Notification event type (repeatable, required)"},destination:{type:"string",description:"Destination as channel:key (repeatable, required)"},"component-id":{type:"string",description:"Component ID to match (repeatable)"},"include-descendants":{type:"boolean",description:"Also match descendant components"},severity:{type:"string",description:`Severity condition: ${Zv.join(", ")} (repeatable)`}},cj=(e,t)=>{let n=_u(e["notification-type"]);if(n.length===0){if(t)h("At least one --notification-type is required (see 'sazabi notifications delivery-rules options').");else g("At least one --notification-type is required (see 'sazabi notifications delivery-rules options').");return null}let r=UW(_u(e.destination),t);if(!r)return null;if(r.length===0){if(t)h("At least one --destination is required (see 'sazabi notifications delivery-rules options').");else g("At least one --destination is required (see 'sazabi notifications delivery-rules options').");return null}let o=MW(_u(e.severity),t);if(!o)return null;let i=_u(e["component-id"]);return{notificationTypes:n,destinations:r,includeDescendants:e["include-descendants"]===!0,condition:o.length>0?{severities:o}:{},...i.length>0?{componentIds:i}:{}}},FW=async(e)=>{let{values:t}=S(e,bi),{client:n,json:r}=vi(t),o=f(await n.notificationDeliveryRules.list(),"Couldn't list delivery rules",r);D(NW,o.rules.map(Jv),{json:r,contract:{response:o,itemsKey:"rules"}})};async function ju(e){let t=await e.client.notificationDeliveryRules.options();if(!e.reportFailure)return f(t,"Couldn't load delivery rule options",e.json);if(t.success)return t.value;return e.reportFailure(`Couldn't load the alert channels. Try this card again. ${t.error}`),null}var Ru=(e)=>{let t=e.channelCatalogs;if(!t)return[];return[...t.slack?.isInitialSyncPending?[{label:"Slack",destinationChannel:"slack_channel"}]:[],...t.microsoftTeams?.isInitialSyncPending?[{label:"Microsoft Teams",destinationChannel:"teams_channel"}]:[]]};async function Eu(e){let{client:t,json:n,reportFailure:r,...o}=e,i=await t.notificationDeliveryRules.create(o);if(!r)return f(i,"Failed to create delivery rule",n);if(i.success)return i.value;return r(`Couldn't save the alert rule. Try this card again. ${i.error}`),null}var BW=async(e)=>{let{values:t}=S(e,bi),{client:n,json:r}=vi(t),o=await ju({client:n,json:r});if(r){j(o);return}D({schema:{channel:{label:"Channel",type:{kind:"string"}},destinationKey:{label:"Key",type:{kind:"string"}},displayName:{label:"Name",type:{kind:"string"}}},columns:["channel","destinationKey","displayName"],header:"Destinations",emptyMessage:"No configured destinations."},o.destinations,{json:!1});for(let i of Ru(o))N(`${i.label} channels are still syncing. Run this command again shortly to see them.`);D({schema:{notificationType:{label:"Event",type:{kind:"string"}},label:{label:"Label",type:{kind:"string"}},conditions:{label:"Conditions",type:{kind:"string"}}},columns:["notificationType","label","conditions"],header:"Notification events",emptyMessage:"No notification events available."},o.notificationTypes.map((i)=>({notificationType:i.notificationType,label:i.label,conditions:i.conditions.join(", ")})),{json:!1}),D({schema:{id:{label:"ID",type:{kind:"string"}},label:{label:"Label",type:{kind:"string"}},lifecycle:{label:"Lifecycle",type:{kind:"string"}}},columns:["id","label","lifecycle"],header:"Components",emptyMessage:"No components registered."},o.components,{json:!1})},GW=async(e)=>{let{values:t}=S(e,{...bi,...sj}),{client:n,json:r}=vi(t),o=cj(t,r);if(!o)return;let i=await Eu({client:n,json:r,...o});if(r){j(i);return}z("Delivery rule created."),R(aj,Jv(i),{json:r})},KW=async(e)=>{let{values:t,positionals:n}=S(e,{...bi,...sj},{allowPositionals:!0}),r=t.json,o=n[0];if(!o){if(r)return h("Delivery rule ID is required. Run 'sazabi notifications delivery-rules list' to see rule IDs.");return g("Delivery rule ID is required. Run 'sazabi notifications delivery-rules list' to see rule IDs.")}let{client:i}=vi(t),a=cj(t,r);if(!a)return;let s=f(await i.notificationDeliveryRules.update({...a,ruleId:o}),"Failed to update delivery rule",r);if(r){j(s);return}z("Delivery rule updated."),R(aj,Jv(s),{json:r})},qW=async(e)=>{let{values:t,positionals:n}=S(e,bi,{allowPositionals:!0}),r=t.json,o=n[0];if(!o){if(r)return h("Delivery rule ID is required. Run 'sazabi notifications delivery-rules list' to see rule IDs.");return g("Delivery rule ID is required. Run 'sazabi notifications delivery-rules list' to see rule IDs.")}let{client:i}=vi(t),a=f(await i.notificationDeliveryRules.delete(o),"Failed to delete delivery rule",r);if(r){j(a);return}z("Delivery rule deleted.")},WW={channel:{label:"Channel",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},scope:{label:"Scope",type:{kind:"string"}},enabled:{label:"Enabled",type:{kind:"string"}},status:{label:"Status",type:{kind:"string"}}},VW=async(e)=>{let{values:t}=S(e,bi),{client:n,json:r}=vi(t),o=f(await n.notificationChannels.getProject(),"Couldn't load notification channels",r);if(r){j(o);return}D({schema:WW,columns:["channel","name","scope","enabled","status"],header:`Notification channels (issue min severity: ${o.issueNotificationMinSeverity})`,emptyMessage:"No notification channels."},o.channelCards.map((i)=>({channel:i.channel,name:i.name,scope:i.scope,enabled:i.enabled===null?"—":i.enabled?"yes":"no",status:i.prerequisite.statusLabel})),{json:!1})},lj=q("notifications","Manage notification delivery rules and inspect channels").withSubcommands({"delivery-rules":v("delivery-rules","Manage project notification delivery rules").withSubcommands({list:v("list","List delivery rules",FW).withOptions(yi).withExamples(["sazabi notifications delivery-rules list # List delivery rules"]).build(),options:v("options","List available destinations, events, and conditions",BW).withOptions(yi).withExamples(["sazabi notifications delivery-rules options # See what you can route"]).build(),create:v("create","Create a delivery rule",GW).withOptions({...yi,...rj}).withExamples(["sazabi notifications delivery-rules create --notification-type issue_triggered --destination slack_channel:C0123 --severity high # Route high-severity issues to Slack"]).build(),update:v("update","Replace a delivery rule (atomic)",KW).withPositionalArgs("<rule-id>").withOptions({...yi,...rj}).withExamples(["sazabi notifications delivery-rules update <id> --notification-type issue_triggered --destination slack_channel:C0123 # Replace a rule"]).build(),delete:v("delete","Delete a delivery rule",qW).withPositionalArgs("<rule-id>").withOptions(yi).withExamples(["sazabi notifications delivery-rules delete <id> # Delete a rule"]).build()}).withExamples(["sazabi notifications delivery-rules list # List delivery rules","sazabi notifications delivery-rules options # See routable destinations and events"]).build(),channels:v("channels","Inspect notification channels").withSubcommands({get:v("get","List the project's notification channels",VW).withOptions(yi).withExamples(["sazabi notifications channels get # List configured channels"]).build()}).withExamples(["sazabi notifications channels get # List configured channels"]).build()}).withExamples(["sazabi notifications delivery-rules list # List delivery rules","sazabi notifications channels get # Inspect channels"]).build();H();var HW=[{id:"set_up_billing",label:"Choose a plan",description:"Choose to continue with Free without a credit card or select a paid plan.",instructions:"Choose Continue with Free to keep your existing plan, or select a paid plan and complete checkout.",category:"onboarding"},{id:"connect_github_account",label:"Connect GitHub account",description:"Link your personal GitHub login so code search can list the repositories you have access to.",instructions:"Go to Settings > Connected Accounts and connect GitHub. You will be redirected to GitHub to authorize your personal account.",category:"onboarding"},{id:"install_github_app",label:"Install GitHub App",description:"Install the Sazabi GitHub App on your GitHub organization to enable code search, pull request mention handling, and repository-triggered agent runs.",instructions:"Go to Settings > Integrations and connect GitHub (install the Sazabi GitHub App on your GitHub organization).",category:"onboarding"},{id:"configure_code_search",label:"Configure code search",description:"Link at least one GitHub repository to your project so agents can search and read your codebase during investigations.",instructions:"Go to Settings > Code Search and click 'Add repository'. Select the GitHub repositories you want agents to have access to.",category:"onboarding"},{id:"install_slack_app",label:"Install Slack App",description:"Connect Slack so your team receives issue alerts and can trigger agent runs from chat.",instructions:"Go to Settings > Integrations and connect Slack. You will be redirected to authorize the Sazabi app on your workspace.",category:"onboarding"},{id:"configure_slack_alerts",label:"Configure Slack alerts",description:"Select a Slack channel to receive issue alerts and agent summaries when something goes wrong in production.",instructions:"Go to Settings > Project Notifications and select a Slack channel for issue alerts. Sazabi will post issue alerts and agent summaries to that channel.",category:"onboarding"},{id:"trigger_sample_issue",label:"Resolve your first issue",description:"Resolve a test issue to see how Sazabi presents an incident: what happened, why it happened, and how to fix it. This shows you the shape of a real issue before your own telemetry produces one.",instructions:"Open the 'Resolve your first issue' step during onboarding and resolve the test issue. From the CLI, run 'sazabi onboarding' and resolve it there.",category:"onboarding"}],Bt=[{kind:"card",id:"set_up_billing"},{kind:"gate",id:"create-project"},{kind:"card",id:"connect_github_account"},{kind:"card",id:"install_github_app"},{kind:"card",id:"configure_code_search"},{kind:"card",id:"install_slack_app"},{kind:"card",id:"configure_slack_alerts"},{kind:"card",id:"trigger_sample_issue"}],Si=new Map(HW.map((e)=>[e.id,e])),nr=Bt.filter((e)=>e.kind==="card").map((e)=>{let t=Si.get(e.id);if(t===void 0)throw Error(`ONBOARDING_FLOW references a card with no definition: ${e.id}`);return t});var uj={configure_code_search:["connect_github_account","install_github_app"],configure_slack_alerts:["install_slack_app"]},ds=(e)=>uj[e]??[],Yv=["connect_github_account","install_github_app","install_slack_app","trigger_sample_issue"],dj=new Set(["connect_github_account","install_github_app","install_slack_app"]),Hn=(e)=>dj.has(e);var pj={set_up_billing:"billing-step-enabled"},ps=(e)=>pj[e]??null,mj=new Set(["trigger_sample_issue"]),Xv=(e)=>!mj.has(e);var gj=[{id:"send_message",label:"Send message",description:"Start your first conversation by sending a message to an agent in any project thread.",instructions:"Open your project and type a message in the composer at the bottom of any thread. Press Enter or click Send to start a conversation.",category:"setup"},{id:"connect_log_sources",label:"Add log sources",description:"Connect a telemetry data source such as Datadog, Sentry, or AWS CloudWatch so agents have access to your logs, metrics, and traces.",instructions:"Go to Settings > Data Sources and click 'Add data source'. Choose a provider such as Datadog, Sentry, or AWS CloudWatch and follow the configuration steps.",category:"setup"},{id:"install_cli",label:"Use Sazabi CLI",description:"Install the Sazabi CLI so you and your coding agents can query logs, search project memory, and manage Sazabi from the terminal. The task is complete once any member of your organization signs in with the CLI.",instructions:"Run 'npm install -g @sazabi/cli' to install the CLI, then 'sazabi auth sign-in' to sign in. The full command reference lives at https://docs.sazabi.com/reference/cli.",category:"setup"},{id:"invite_team",label:"Invite team",description:"Invite at least one other team member so your whole team can collaborate on investigations and share context.",instructions:"Go to Settings > Members and click 'Invite member'. Enter your teammate's email address and select their role.",category:"setup"},{id:"configure_auto_top_up",label:"Set up auto top-up",description:"Turn on automatic credit reloads so agents never pause mid-investigation when your balance runs low. Auto top-up adds credits automatically whenever your balance falls below a threshold you choose.",instructions:"Go to Settings > Billing and enable automatic reload under Auto top-up. Choose the balance threshold that triggers a reload and the amount to add each time.",category:"setup"},{id:"add_mcp_connectors",label:"Add MCP connectors",description:"Add a Model Context Protocol (MCP) connector to extend agent capabilities with tools from external services.",instructions:"Go to Settings > MCP Connectors and click 'Add connector'. Choose a connector from the available list and follow the setup steps.",category:"setup"},{id:"customize_sandbox",label:"Connect sandbox CLIs",description:"Connect a sandbox CLI so agents can use your infrastructure and deployment tooling from inside the agent sandbox during investigations.",instructions:"Go to Settings > Sandbox CLIs and connect a CLI. Sazabi validates the credentials and makes the CLI available in every agent sandbox for this project.",category:"setup"},{id:"explore_integrations",label:"Explore integrations",description:"Visit the integrations page to discover available third-party integrations for your project.",instructions:"Go to Settings > Integrations to browse the available integrations. Click any integration to view setup instructions and connect it to your project.",category:"setup"},{id:"visit_status_page",label:"Visit status page",description:"Visit your project's status page to see how Sazabi monitors and displays the health of your services.",instructions:"Click 'Status Page' in the project navigation sidebar to open your project's public status page.",category:"setup"}];var Qv="trigger_sample_issue",jt={name:"Checkout error spike",component:"checkout-api",severity:"high",description:"Checkout errors jumped from 0.2% to 4.8% right after a deploy, and the failures cluster on payment-provider timeouts at confirmation. That deploy changed the retry policy, so retries now stack on slow responses and exhaust the provider's rate limit. Roll it back to restore normal error rates, then reintroduce it with capped retries and a call-time budget."},Lu="Description",eS="Sazabi opens an issue when something breaks, with details on what happened and how to fix it. Resolve this one to continue.",ms={open:"Open",resolved:"Resolved"},tS=2700000,nS=(e=new Date)=>new Date(e.getTime()-tS),oS=()=>`${Math.round(tS/60000)}m ago`,hj=Si.get(Qv);if(hj===void 0)throw Error(`The onboarding registry has no '${Qv}' card for the test-issue exhibit.`);var rS=hj.label;var wAe=[...nr,...gj];var CAe=new Set(nr.map((e)=>e.id));var ZW=(e,t)=>{let n=ds(e);return n.length>0&&n.every((r)=>t(r))},JW=(e,t)=>{if(ZW(e,t.skipped))return!1;let n=ps(e);return n===null||(t.applies?.(n)??!0)};var zu=(e,t,n)=>{let r=Bt.findIndex((o)=>o.id===t);if(r===-1)return null;if(n===-1&&t!=="create-project"&&!Xv(t))return null;for(let o=r+n;o>=0&&o<Bt.length;o+=n){let i=Bt[o];if(i===void 0)continue;if(i.kind==="gate")return i;if(Si.has(i.id)&&JW(i.id,e))return i}return null};te();Qe();H();var iS={done:"✓",current:"→",muted:"–"};var YW=(e)=>{switch(e.kind){case"done":return _.success(iS.done);case"current":return _.info(iS.current);default:return _.muted(iS.muted)}},XW=(e)=>{if(e.state.kind==="skipped")return"skipped";return e.detail?.trim()??""},fj=(e)=>{if(e.state.kind==="hidden")return null;let t=XW(e),n=t?` ${_.muted(`(${t})`)}`:"";return` ${YW(e.state)} ${e.label}${n}`},QW=(e,t)=>{switch(t.state){case"done":return{kind:"done"};case"pending":return{kind:"current"};case"skipped":return{kind:"skipped"};case"not-applicable":return{kind:"hidden"};case"unavailable":return{kind:"hidden"}}},or=(e)=>fj({label:e.card.label,state:QW(e.card,e.status),detail:e.detail}),eV=(e)=>e.state==="complete"?{kind:"done"}:{kind:"current"},Ii=(e)=>e.step.listed===!1?null:fj({label:e.step.title,state:eV(e.status),detail:e.status.state==="complete"?e.detail:null}),ki=async(e,t)=>await e.doneNote?.(t)??null;H();se();te();Qe();var aS={"verify-email":"Verify your email","accept-invite":"Accept your invitation","create-organization":"Create an organization",billing:"Set up billing","configure-project":"Configure the project","connect-github-account":"Connect your GitHub account","install-github-app":"Install the forge app","configure-code-search":"Configure code search","install-slack-app":"Install the chat app","configure-slack-notifications":"Configure alerts","trigger-issue":"Trigger the test issue","confirm-issue":"Resolve the test issue",finish:"Finish onboarding"},tV=(e,t)=>{let n=e.token?.trim()||process.env.SAZABI_TOKEN?.trim()||t.token?.trim()||"",r=e.organizationId||process.env.SAZABI_ORGANIZATION_ID?.trim()||"",o=e.projectId||process.env.SAZABI_PROJECT_ID?.trim()||"",i=r||t.activeOrganizationId||void 0,a=o||t.activeProjectId||void 0;return{token:n,organizationId:i,projectId:a,explicitScope:{organizationId:r.length>0,projectId:o.length>0}}},cS=async(e,t)=>{let n=await e.onboarding.getState(t?{projectId:t}:{});return{tasks:n.success?n.value.onboarding.tasks:[],tasksError:n.success?null:n.error,state:n.success?n.value.onboarding:null,stateError:n.success?null:n.error}},ko=(e)=>e.snapshot.tasksError??e.snapshot.stateError,hs=(e)=>e.snapshot.stateError,Du=Bt.findIndex((e)=>e.kind==="gate"),nV=new Map(nr.map((e)=>[e.id,e])),vj=(e)=>e.flatMap((t)=>{if(t.kind!=="card")return[];let n=nV.get(t.id);return n?[n]:[]}),$u=vj(Du===-1?[]:Bt.slice(0,Du)),wi=vj(Du===-1?Bt:Bt.slice(Du)),lS=async(e)=>{if(!e.projectId||!e.organizationId)return Re(void 0);let t=await e.client.projects.get(e.projectId),n=()=>we(`The selected project (${e.projectId}) isn't in the active organization. Check --project-id/SAZABI_PROJECT_ID, or run 'sazabi projects use <id>' after 'sazabi organizations use <id>'.`);if(t.success){if(t.value.project.organizationId!==e.organizationId)return n();return Re(void 0)}if(t.statusCode===404||t.statusCode===403)return n();return Re(void 0)},Uu=async(e)=>{let t=Boolean(e.json),n=f(vt(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t),{token:r,organizationId:o,projectId:i,explicitScope:a}=tV(e,n),s=T({token:r,organizationId:o,projectId:i,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:t}),c=r?await cS(s,i):{tasks:[],tasksError:null,state:null,stateError:null},l=Jt({apiBaseUrlFlag:e.apiBaseUrl,jsonMode:t});return{client:s,profile:n,organizationId:o,projectId:i,explicitScope:a,hasCredentials:r.length>0,apiBaseUrl:l,platformApiBaseUrl:oV({apiBaseUrl:l,apiBaseOverridden:Boolean(e.apiBaseUrl?.trim()||process.env.SAZABI_API_URL?.trim()),profileAuthBaseUrl:n.authBaseUrl}),webAppUrl:ti({apiBaseUrlFlag:e.apiBaseUrl,jsonMode:t}),snapshot:c,prompts:{select:qo,multiselect:Ha,text:Za,confirm:ri,waitForEnter:ii},json:t}},oV=(e)=>nu(e.apiBaseUrl,e.apiBaseOverridden?void 0:e.profileAuthBaseUrl);var uS=(e)=>{if(e.state?.hasPaidBillingSubscription)return!0;return e.tasks.some((t)=>t.id==="set_up_billing"&&t.status==="complete")},fs=(e,t)=>e.snapshot.tasks.find((n)=>n.id===t)?.status,Sj=(e)=>{let t=e.snapshot.state;if(!t)return!0;return t.billingStepEnabled||uS(e.snapshot)},Ci=(e)=>({done:(t)=>t==="set_up_billing"?uS(e.snapshot):fs(e,t)==="complete",skipped:(t)=>fs(e,t)==="skipped",applies:(t)=>{switch(t){case"billing-step-enabled":return Sj(e)}},status:(t)=>fs(e,t)}),Nu=(e)=>({done:(t)=>t==="set_up_billing"?uS(e.snapshot):fs(e,t)==="complete",skipped:()=>!1,applies:(t)=>{switch(t){case"billing-step-enabled":return Sj(e)}},status:(t)=>fs(e,t)}),un=(e,t)=>{if(t.done(e.id))return{state:"done"};let n=ps(e.id);if(n!==null&&!(t.applies?.(n)??!0))return{state:"not-applicable"};switch(t.status(e.id)){case"skipped":return{state:"skipped"};case"unavailable":return{state:"unavailable",dependency:ds(e.id)[0]};default:return{state:"pending"}}},rV=(e)=>{let t=Ci(e);return nr.map((n)=>({card:n,status:un(n,t)}))},Ij=(e)=>{let t=ko(e);if(t===null)return{kind:"ready",rows:rV(e)};if(!e.projectId&&hs(e)===null){let n=Nu(e);return{kind:"org-only",rows:$u.map((r)=>({card:r,status:un(r,n)}))}}return{kind:"read-error",error:t}},Zn=async(e,t)=>{try{return await t.check(e)}catch(n){return{state:"incomplete",reason:`Couldn't check this step: ${n instanceof Error?n.message:String(n)}`}}},sS=(e)=>Yv.includes(e),iV=async(e)=>{let{ctx:t,cardId:n}=e;if(!sS(n))return we(`${n} is not a skippable onboarding task.`);if(!t.organizationId&&!t.projectId)return we("No active organization to record the skip against. Select one first.");let r=await le({label:oe({what:"Recording the skip"}),json:t.json,work:()=>t.client.tasks.skip({taskId:n,...Mu(t)})});if(!r.success)return r;return Re(void 0)},Mu=(e)=>{let t=Boolean(e.explicitScope?.organizationId&&e.organizationId),n=Boolean(e.explicitScope?.projectId&&e.projectId);if(t&&n)return{organizationId:e.organizationId,projectId:e.projectId};if(n)return{projectId:e.projectId};if(t)return{organizationId:e.organizationId};if(e.organizationId)return{organizationId:e.organizationId};if(e.projectId)return{projectId:e.projectId};return{}},aV=(e)=>{let{preambleStatuses:t,projectGateStatus:n,ctx:r,interpreter:o,webBaseUrl:i}=e,a=(I)=>I.status.state==="incomplete"?{payload:{step:I.step.id,reason:I.status.reason,actions:I.step.instructions(r)},exitCode:2}:null,s=(I)=>({payload:{step:null,reason:`Couldn't load the onboarding state (${I}). Retry shortly.`,actions:[]},exitCode:2}),c=(I)=>{let C=I.find(({card:B,status:V})=>!Hn(B.id)&&V.state==="pending");if(!C)return null;return{payload:{step:C.card.id,reason:C.card.description,actions:o.instructions(C.card,r)},exitCode:2}};for(let I of t){let C=a(I);if(C)return C}let l=hs(r);if(l)return s(l);let u=Nu(r),d=c($u.map((I)=>({card:I,status:un(I,u)})));if(d)return d;if(n){let I=a(n);if(I)return I}let p=ko(r);if(p)return s(p);let m=Ci(r),b=c(wi.map((I)=>({card:I,status:un(I,m)})));if(b)return b;let y=kj(r.snapshot.state);return{payload:{step:null,reason:y.length>0?"All required onboarding steps are complete. Finish the remaining steps in the dashboard.":"All required steps are complete.",actions:y.map((I)=>({url:`${i}/onboarding`,description:aS[I]}))},exitCode:y.length>0?2:0}},kj=(e)=>{if(!e||e.isCompleted)return[];return Object.entries(e.completionByStep).filter(([t,n])=>n==="incomplete"&&t!=="finish").map(([t])=>t)},dS={id:"finish",title:"Finish onboarding",check:async(e)=>e.snapshot.state?.isCompleted?{state:"complete",detectedFrom:"server"}:{state:"incomplete",reason:"Onboarding is not finished yet."},instructions:()=>[{command:"sazabi onboarding continue",description:"Finish onboarding"}]},sV=6000,cV=750,yj=async(e)=>{let t=e.snapshot.state;if(!t){let n=await e.client.onboarding.getState(e.projectId?{projectId:e.projectId}:{});if(!n.success)return{outcome:"unavailable"};t=n.value.onboarding}if(t.isCompleted)return{outcome:"already-complete"};if(t.canonicalStep==="finish"&&e.projectId){if(await le({label:oe({what:"Finishing onboarding"}),json:e.json,work:async()=>{let r=Date.now()+sV;for(;;){if((await e.client.onboarding.finish({projectId:e.projectId})).success)return!0;if(Date.now()>=r)return!1;await new Promise((i)=>setTimeout(i,cV))}}}))return{outcome:"finished"};return{outcome:"unavailable"}}return{outcome:"web-steps-remaining",webSteps:kj(t)}},lV={out:(e)=>console.log(e),isInteractive:ke},bj="Paused. Resume anytime with sazabi onboarding continue.",rr={label:mo,value:"quit"},FAe=_.success("✓"),uV=_.info("→"),gs=_.muted("○"),BAe=_.muted("–"),dV={connect_github_account:"GitHub account connected",install_github_app:"GitHub App installed. Continue to choose repositories.",configure_code_search:"Code search configured",install_slack_app:"Slack app installed. Continue to the next step.",configure_slack_alerts:"Slack alerts configured",trigger_sample_issue:"Issue resolved"},wj=async(e)=>{let{preamble:t,projectGate:n,interpreter:r,json:o}=e,i=e.io??lV,a=e.webBaseUrl??on(),s=!1,c=!1,l=async(J="Refreshing your setup")=>le({label:oe({what:J}),json:o,work:e.buildContext}),u=e.initialContext??await l("Loading your setup"),d=async(J)=>{let X;try{X=await e.buildContext()}catch{return null}return J(X)===null?X:null},p=async(J)=>{let X=await le({label:oe({what:"Refreshing your setup"}),json:o,work:()=>d(J)});if(X!==null)u=X},m=async(J)=>await le({label:oe({what:"Checking what's done"}),json:o,work:async()=>await r.doneNote?.(J,u)??null})??null,b=new Map,y=(J)=>`gate:${J.id}`,I=async()=>{if(o||!i.isInteractive())return;let J=[],X=(pe)=>Promise.resolve(r.doneNote?.(pe,u)).then((Ie)=>b.set(pe.id,Ie??null)).catch(()=>b.set(pe.id,null));if(hs(u)===null){let pe=Nu(u);for(let Ie of $u)if(un(Ie,pe).state==="done")J.push(X(Ie))}if(n&&u.projectId)J.push(ki(n,u).then((pe)=>b.set(y(n),pe)).catch(()=>b.set(y(n),null)));if(u.projectId&&ko(u)===null){let pe=Ci(u);for(let Ie of wi)if(un(Ie,pe).state==="done")J.push(X(Ie))}if(J.length===0)return;await le({label:oe({what:"Loading your setup"}),json:o,work:()=>Promise.all(J)})};if(o||!i.isInteractive()){let J=[];for(let ht of t)J.push({step:ht,status:await Zn(u,ht)});let{payload:X,exitCode:pe}=aV({preambleStatuses:J,projectGateStatus:n?{step:n,status:await Zn(u,n)}:null,ctx:u,interpreter:r,webBaseUrl:a});if(pe!==0)return j(X),pe;let Ie=await yj(u);if(Ie.outcome==="finished"||Ie.outcome==="already-complete")return j(X),0;let Rt=Ie.outcome==="web-steps-remaining"?Ie.webSteps:[];return j({step:null,reason:Rt.length>0?"All required onboarding steps are complete. Finish the remaining steps in the dashboard.":"All required onboarding steps are complete. Finish onboarding in the dashboard.",actions:Rt.length>0?Rt.map((ht)=>({url:`${a}/onboarding`,description:aS[ht]})):[{url:`${u.webAppUrl}/onboarding/finish`,description:"Finish onboarding"}]}),2}Gb(bj),i.out(""),i.out(_.bold("Sazabi onboarding")),i.out(""),await I();let C=(J)=>(i.out(""),i.out(_.warning(`Couldn't load the onboarding state (${J}).`)),i.out(_.muted("Try again in a moment: sazabi onboarding continue")),1),B=()=>(i.out(""),i.out(_.muted(bj)),0),V=async(J)=>{let X=async()=>{u=await l(),b.clear(),await I()},pe=async(Me)=>{let Gt=y(J),_n=!c&&b.has(Gt)?b.get(Gt)??null:await le({label:oe({what:"Checking what's done"}),json:o,work:()=>ki(J,u)}),de=Ii({step:J,status:Me,detail:_n});if(de!==null)i.out(de)},Ie=await Zn(u,J);if(Ie.state==="complete")return await pe(Ie),null;if(await X(),Ie=await Zn(u,J),Ie.state==="complete")return await pe(Ie),null;let Rt=await J.run?.(u);if(Rt==="quit")return B();if(Rt==="created"&&J.id==="create_project")s=!0;await X();let ht=await Zn(u,J);if(ht.state==="complete")return await pe(ht),null;return i.out(J.listed===!1?_.muted(ht.reason):` ${gs} ${J.title} ${_.muted("(still shows incomplete)")}`),i.out(""),i.out(_.muted("The onboarding tour needs this step first. Run 'sazabi onboarding continue' once it's complete.")),0};for(let J of t){let X=await V(J);if(X!==null)return X}let ee=0,Z=!1,re=async(J,X,pe,Ie=null,Rt=null)=>{let ht=Rt===null?-1:J.findIndex((de)=>de.id===Rt),Me=ht===-1?0:ht;if(ht!==-1)c=!0;let Gt=null,_n=async(de)=>{await p(pe);let He=zu(X(u),de.id,-1);if(He===null)return;if(He.kind==="gate"){if(Ie){if(await Ie("back")==="quit")return"quit";await p(pe),Me=0,c=!0}return}let pr=J.findIndex((Ri)=>Ri.id===He.id);if(pr===-1)return;Me=pr,c=!0};while(Me<J.length){let de=J[Me],He=un(de,X(u));if(He.state==="not-applicable"){Me+=1;continue}if(c&&He.state==="done"){if(Gt===de.id)Gt=null,i.out(or({card:de,status:He,detail:await m(de)})??"");let Ce=He.state==="done"?r.revisit?.(de)??null:null;if(Ce!==null){let be=await Ce(u);if(be==="back"){if(await _n(de)==="quit")return B();continue}if(be==="hold")return B();u=await l();let De=pe(u);if(De!==null)return C(De);Me+=1;continue}await r.renderRevisit?.(de,u);let Et=zu(X(u),de.id,-1),ne=await u.prompts.select({message:dV[de.id]??de.label,echoAnswer:!1,choices:[{label:"Continue",value:"continue",preselected:!0},...Et!==null?[{label:Cn,value:"back"}]:[],rr]});if(ne==="quit")return B();if(ne==="back"){if(await _n(de)==="quit")return B();continue}if(await p(pe),un(de,X(u)).state!=="done")continue;Me+=1;continue}if(!c){if(He.state==="done"){let Ce=b.has(de.id)?b.get(de.id)??null:await m(de);i.out(or({card:de,status:{state:"done"},detail:Ce})??""),Me+=1;continue}if(He.state==="skipped"){i.out(or({card:de,status:{state:"skipped"}})??""),Me+=1;continue}}if(He.state==="unavailable"){Me+=1;continue}u=await l();{let Ce=pe(u);if(Ce!==null)return C(Ce)}if(He=un(de,X(u)),!(He.state==="pending"||He.state==="skipped"))continue;Gt=null;let mr=He.state==="skipped";c=!0;let Ls=zu(X(u),de.id,-1);if(Hn(de.id)){let Ce=await u.prompts.select({message:`${de.label}?`,echoAnswer:!1,choices:[{label:"Yes",value:"configure",preselected:!0},{label:"Skip",value:"skip"},...Ls!==null?[{label:Cn,value:"back"}]:[],rr]});if(Ce==="quit")return B();if(Ce==="back"){if(await _n(de)==="quit")return B();continue}if(Ce==="skip"){let Et=await iV({ctx:u,cardId:de.id});if(!Et.success){i.out(` ${gs} ${de.label} ${_.warning(`(couldn't save the skip: ${Et.error}; it will prompt again next run)`)}`),Me+=1;continue}u=await l();{let ne=pe(u);if(ne!==null)return C(ne)}Me+=1;continue}}else if(Ls!==null&&!r.ownsBackAffordance?.(de)){let Ce=await u.prompts.select({message:`${de.label}?`,choices:[{label:"Continue",value:"continue",preselected:!0},{label:Cn,value:"back"},rr]});if(Ce==="quit")return B();if(Ce==="back"){if(await _n(de)==="quit")return B();continue}}let Ei=async(Ce)=>{let Et=await le({label:oe({what:"Reopening the step"}),json:o,work:()=>u.client.tasks.unskip({taskId:Ce,...Mu(u)})});if(!Et.success)return i.out(` ${gs} ${de.label} ${_.warning(`(couldn't clear the skip: ${Et.error}; it stays skipped)`)}`),"failed";return"cleared"},Li=r.ownsBackAffordance?.(de)??!1;if(mr&&sS(de.id)&&!Li){if(await Ei(de.id)==="failed"){Me+=1;continue}u=await l();{let Ce=pe(u);if(Ce!==null)return C(Ce)}}let zi=await r.run(de,u);if(zi==="back"){if(await _n(de)==="quit")return B();continue}if(zi==="hold")return B();if(mr&&sS(de.id)&&Li){if(await Ei(de.id)==="failed"){Me+=1;continue}}u=await l();{let Ce=pe(u);if(Ce!==null)return C(Ce)}let Di=un(de,X(u));if(Di.state==="done")i.out(or({card:de,status:{state:"done"},detail:await m(de)})??""),Me+=1;else if(Di.state==="skipped"&&!mr)Me+=1;else{if(i.out(` ${gs} ${de.label} ${_.muted("(still shows incomplete; detection can take a moment)")}`),Hn(de.id)&&i.isInteractive()&&!o){Gt=de.id;continue}if(Z=!0,!Hn(de.id))ee+=1;break}}return null};{let J=hs(u);if(J!==null)return C(J)}{let J=await re($u,Nu,hs);if(J!==null)return J}let ge=async(J)=>{let X=n?await ki(n,u):null;if(n&&J==="forward")i.out(Ii({step:n,status:{state:"complete",detectedFrom:"local"},detail:X})??"");if(await u.prompts.select({message:X?`Project created (${X})`:"Project created",echoAnswer:!1,choices:[{label:"Continue",value:"continue",preselected:!0},rr]})==="quit")return"quit"};if(!Z&&ee===0){if(n){let X=await Zn(u,n);if(c&&X.state==="complete"){if(await ge("forward")==="quit")return B();await p(ko)}else{let pe=await V(n);if(pe!==null)return pe;if(s)c=!0}}{let X=ko(u);if(X!==null)return C(X)}let J=await re(wi,Ci,ko,ge);if(J!==null)return J}i.out("");let Se=()=>{i.out(_.muted(`${ee} required ${ee===1?"step remains":"steps remain"}. Run 'sazabi onboarding continue' to resume.`))},Ee=()=>{i.out(_.muted("Run 'sazabi onboarding continue' to retry, or skip the step to move on."))};if(ee>0)return Se(),0;if(Z)return Ee(),0;let Ve=()=>{let J=Ci(u);for(let X=wi.length-1;X>=0;X-=1){let pe=wi[X],Ie=un(pe,J).state;if(Ie!=="not-applicable"&&Ie!=="unavailable")return pe}return null};if(i.isInteractive()&&!o&&!u.snapshot.state?.isCompleted)for(;;){if(Ve()===null){await u.prompts.waitForEnter("Press Enter to finish onboarding");break}let X=await u.prompts.select({message:"Finish onboarding?",choices:[{label:"Finish",value:"finish",preselected:!0},{label:Cn,value:"back"},rr]});if(X==="quit")return B();if(X!=="back")break;await p(ko);let pe=Ve();if(pe===null)continue;let Ie=await re(wi,Ci,ko,ge,pe.id);if(Ie!==null)return Ie;if(ee>0)return Se(),0;if(Z)return Ee(),0;i.out("")}let Qt=await yj(u);if(Qt.outcome==="finished"||Qt.outcome==="already-complete")i.out(Ii({step:dS,status:{state:"complete",detectedFrom:"server"},detail:null})??""),i.out(_.success("Onboarding complete."));else if(Qt.outcome==="web-steps-remaining"){i.out("Remaining steps to finish in the dashboard:");for(let J of Qt.webSteps)i.out(` ${uV} ${aS[J]}: ${_.info(`${a}/onboarding`)}`)}else i.out(` ${gs} Finish onboarding in the dashboard: ${_.info(`${u.webAppUrl}/onboarding/finish`)}`);return 0};H();H();var Cj={run:async(e)=>{let t=Boolean(e.snapshot?.state?.hasServiceableBillingSubscription&&!e.snapshot.state.hasPaidBillingSubscription),n=await le({label:oe({what:"Loading the available plans"}),json:e.json,work:()=>e.client.billing.listPlans()});if(!n.success&&!t){gt(n,"Couldn't fetch plans. Try this card again");return}let r=n.success?n.value.plans.filter((a)=>a.isVisible!==!1):[];if(!n.success&&t)N("Paid plans couldn't be loaded. You can continue with Free and upgrade later.");if(r.length===0&&!t){N("No self-serve plans are available. Set up billing from the dashboard.");return}go();let o=await e.prompts.select({message:"Choose a plan",choices:[...t?[{label:"Continue with Free",value:"free-v1",hint:"No credit card required",preselected:!0}]:[],...r.map((a,s)=>({label:a.name,value:a.slug,hint:`${a.price} ${a.currency.toUpperCase()}`,preselected:!t&&s===0}))]});if(o==="free-v1"&&t){if(gt(await le({label:oe({what:"Confirming your Free plan"}),json:e.json,work:()=>e.client.onboarding.continueWithFree(Mu(e))}),"Couldn't confirm your Free plan. Try this card again")===null)return;return}let i=!e.json&&ke()?an():null;try{if(await ov({client:e.client,planSlug:o,json:e.json,completionFact:async()=>Boolean((await cS(e.client,e.projectId)).state?.hasPaidBillingSubscription),cancellation:i??void 0,reportFailure:Ue,announceCompletion:!1}),i?.requested())Yt("Cancelled. Billing is not set up.")}finally{i?.dispose()}},doneNote:async(e)=>{let t=e.snapshot?.state;if(!t)return null;let n=await e.client.billing.getSummary({});if(n.success&&n.value.planName)return n.value.planName;return t.hasServiceableBillingSubscription&&!t.hasPaidBillingSubscription?"Free":null},instructions:(e)=>[{url:`${e.webAppUrl}/onboarding/billing`,description:"Choose a plan in the dashboard"},{command:"sazabi onboarding continue",description:"Interactive: choose Continue with Free at the plan prompt (no credit card required)"},{command:"sazabi billing plans list",description:"List paid plans"},{command:"sazabi billing plans subscribe --plan <slug>",description:"Subscribe via browser checkout"}]};H();lt();var dn={IN_APP:"in_app",SLACK:"slack",SLACK_CHANNEL:"slack_channel",MICROSOFT_TEAMS_CHANNEL:"teams_channel",EMAIL:"email",SMS:"sms",INCIDENT_IO:"incident_io",PAGERDUTY:"pagerduty",ROOTLY:"rootly",WEBHOOK:"webhook"},QAe=[dn.IN_APP,dn.SLACK,dn.EMAIL,dn.SMS],pV=[dn.SLACK_CHANNEL,dn.MICROSOFT_TEAMS_CHANNEL,dn.INCIDENT_IO,dn.PAGERDUTY,dn.ROOTLY,dn.WEBHOOK],Fu=Object.values(dn),eTe=[...Fu,"victorops"],tTe=k.enum(Fu),nTe=k.enum(pV);var mV=[{channel:"in_app",name:"In-app",description:"Show notifications in your Sazabi notification feed.",scope:"personal",destinationManagement:"none",personalSettingsPath:"notifications"},{channel:"email",name:"Email",description:"Send notifications to your account email address.",scope:"personal",destinationManagement:"none",personalSettingsPath:"notifications"},{channel:"sms",name:"SMS",description:"Send notifications to your verified phone number.",scope:"personal",destinationManagement:"none",personalSettingsPath:"account?phone-number=add"},{channel:"slack",name:"Slack DMs",description:"Send personal notifications by Slack DM.",scope:"personal",destinationManagement:"none",personalSettingsPath:"connected-accounts/slack"},{channel:"slack_channel",name:"Slack",description:"Post this project's alerts to selected Slack channels.",scope:"project",destinationManagement:"slack_channels",projectIntegrationPath:"slack"},{channel:"teams_channel",name:"Microsoft Teams",description:"Post this project's alerts to selected Microsoft Teams channels.",scope:"project",destinationManagement:"teams_channels",projectIntegrationPath:"teams"},{channel:"incident_io",name:"incident.io",description:"Route this project's alerts to incident.io.",scope:"project",destinationManagement:"integration_connections",projectIntegrationPath:"incident-io"},{channel:"pagerduty",name:"PagerDuty",description:"Route this project's alerts to PagerDuty.",scope:"project",destinationManagement:"integration_connections",projectIntegrationPath:"pagerduty"},{channel:"rootly",name:"Rootly",description:"Route this project's alerts to Rootly.",scope:"project",destinationManagement:"integration_connections",projectIntegrationPath:"rootly"},{channel:"webhook",name:"Webhooks",description:"Send this project's alerts to configured HTTPS endpoints.",scope:"project",destinationManagement:"webhook_endpoints",projectSettingsPath:"webhooks"}];var Pj=new Set(mV.map(({channel:e})=>e));if(Pj.size!==Fu.length||Fu.some((e)=>!Pj.has(e)))throw Error("Notification channel definitions must represent every channel");var gV=/^[a-z0-9_-]{1,80}$/,pS=(e)=>e.trim().replace(/^#/,"").trim().replace(/\s+/g,"-").toLowerCase(),Oj=(e)=>gV.test(e);var xj=async(e,t)=>{if(e.json)return"hold";return await e.prompts.select({message:t,choices:[{label:Cn,value:"back",preselected:!0},{label:mo,value:"quit"}]})==="back"?"back":"hold"},ir=async(e)=>xj(e,"Nothing to pick yet"),Pi=async(e)=>xj(e,"Couldn't load this card");var hV=3000,jj=90000,mS={action:"keep-routing"},Aj=(e)=>typeof e==="object"&&e!==null&&("action"in e)&&e.action==="create-slack-channel",fV=(e,t)=>{let n=pS(e);if(!Oj(n))return null;if(t.destinations.some((o)=>o.channel==="slack_channel"&&pS(o.displayName)===n))return null;return{label:`Create #${n}`,value:{action:"create-slack-channel",name:n}}},pn=(e)=>`${e.channel}:${e.destinationKey}`,yV=(e)=>{let t=e.destinations.filter((r)=>r.channel==="slack_channel"),n=t.filter((r)=>r.isDeliverable!==!1);return{options:{...e,destinations:n},hiddenPrivate:t.length-n.length}},Rj={slack_channel:"Slack",teams_channel:"Microsoft Teams",incident_io:"incident.io",pagerduty:"PagerDuty",rootly:"Rootly",webhook:"Webhooks"},Tj=Object.keys(Rj),bV=(e)=>[...e].sort((t,n)=>Tj.indexOf(t.channel)-Tj.indexOf(n.channel)),gS=(e)=>Ru(e).filter((t)=>!e.destinations.some((n)=>n.channel===t.destinationChannel)),vV=async(e)=>{let t=Date.now()+jj,n=null,r=await le({label:oe({what:"Loading your alert channels"}),json:e.json,work:()=>ju({client:e.client,json:e.json,reportFailure:(a)=>{n=a}})});if(r===null){if(n!==null)Ue(n);return null}let o=r,i=gS(o);if(i.length===0)return o;return le({label:oe({what:`Waiting for ${i.map((a)=>a.label).join(" and ")} to finish syncing channels`}),json:e.json,work:async()=>{while(gS(o).length>0&&Date.now()<t){await new Promise((s)=>setTimeout(s,hV));let a=await ju({client:e.client,json:e.json,reportFailure:()=>{}});if(a===null)break;o=a}return o}})},SV=async(e,t,n)=>{let r=await le({label:oe({what:"Creating the Slack channel"}),json:e.json,work:()=>e.client.integrations.createSlackChannel({name:n})});if(!r.success)return Fe(r.statusCode===404?"This environment's API does not support creating Slack channels yet.":r.error),null;mt(`#${r.value.name} created in Slack`);let o={id:`slack_channel:${r.value.id}`,channel:"slack_channel",destinationKey:r.value.id,displayName:r.value.name,isDeliverable:r.value.isMember},i=pn(o),a=t.destinations.some((s)=>pn(s)===i);return{options:{...t,destinations:a?t.destinations:[...t.destinations,o]},createdDestinationId:i}},IV=(e,t,n=!1)=>{let r=bV(e.destinations).map((o)=>({label:o.displayName,value:o,group:Rj[o.channel],preselected:t.has(pn(o))}));if(n)r.push({label:"Keep current routing",value:mS,action:!0});return r.push(Ql()),r.push(eu()),r},Ej=async(e,t,n)=>{let r=await vV(e);if(r===null)return await Pi(e)==="back"?"back":"quit";let o=yV(r),i=o.options;if(o.hiddenPrivate>0)N(`${o.hiddenPrivate} private ${o.hiddenPrivate===1?"channel isn't":"channels aren't"} listed: invite the Sazabi app to ${o.hiddenPrivate===1?"it":"them"} in Slack first.`);if(i.destinations.length===0&&i.channelCatalogs?.slack)N("No channels listed yet. Type a name to create one.");if(i.destinations.length===0&&!i.channelCatalogs?.slack)return N(Ru(i).length>0?"Channels are still syncing. Re-run 'sazabi onboarding continue' in a moment.":"No alert destinations available yet. Re-run 'sazabi onboarding continue' in a moment."),await ir(e)==="back"?"back":null;for(let s of gS(i))N(`${s.label} channels are still syncing after ${Pn(jj)} and are not listed yet. Re-run 'sazabi onboarding continue' later to route alerts to them.`);let a=new Set(t);for(;;){let s=new Set(i.destinations.map(pn));if(n){n.clear();for(let m of s)n.add(m)}let c=[...t].some((m)=>!s.has(m)),l=await e.prompts.multiselect({message:"Choose alert channels",itemNoun:"channels",requireExplicitSelection:!0,choices:IV(i,a,c),...i.channelCatalogs?.slack?{createRow:(m)=>fV(m,i)}:{}});if(l.includes(oi))return"quit";if(l.includes(ni))return"back";if(l.includes(mS))return"keep";let u=l.filter((m)=>!Aj(m)&&m!==ni&&m!==oi&&m!==mS),d=l.find(Aj);if(!d)return u;a.clear();for(let m of u)a.add(pn(m));let p=await SV(e,i,d.name);if(p){if(i=p.options,p.createdDestinationId)a.add(p.createdDestinationId)}}},hS=["issue_triggered"],kV=["issue_triggered","issue_resolved","issue_ignored"],_j=(e,t)=>e.length===t.length&&t.every((n)=>e.includes(n)),wV=(e)=>Object.values(e??{}).every((t)=>t===void 0||t===null||Array.isArray(t)&&t.length===0),Lj=(e)=>e.filter((t)=>t.components.length===0&&!t.includeDescendants&&wV(t.condition)&&(_j(t.notificationTypes,hS)||_j(t.notificationTypes,kV))).sort((t,n)=>t.createdAt.localeCompare(n.createdAt)),CV=async(e)=>{let t=await Ej(e,new Set);if(t===null)return"hold";if(t==="back")return"back";if(t==="quit")return"hold";if(t==="keep")return;if(t.length===0){N("No channels selected. Pick at least one channel to save the alert rule, or press Ctrl-C to configure alerts later.");return}let n=null;if(await le({label:oe({what:"Saving your alert channels"}),json:e.json,work:()=>Eu({client:e.client,json:e.json,reportFailure:(o)=>{n=o},destinations:t.map((o)=>({channel:o.channel,destinationKey:o.destinationKey})),notificationTypes:[...hS],includeDescendants:!1,condition:{}})})===null){if(n!==null)Ue(n);return}},PV=async(e)=>{let t=gt(await le({label:oe({what:"Loading your alert rules"}),json:e.json,work:()=>e.client.notificationDeliveryRules.list()}),"Couldn't load the alert delivery rules. Try this card again");if(t===null)return await Pi(e);let n=Lj(t.rules),r=new Set(n.flatMap((I)=>I.destinations.map(pn))),o=await OV(e,r);if(o===null)return"hold";if(o==="back")return"back";if(o==="quit")return"hold";if(o==="keep")return;let{selected:i,offered:a}=o,s=[...r].filter((I)=>!a.has(I));if(s.length>0)N(`${s.length} routed ${s.length===1?"channel isn't":"channels aren't"} listed right now (disconnected or still syncing) and ${s.length===1?"was":"were"} left in place.`);let c=new Set(s);if(i.length===0){N("No channels selected. Alerts need at least one channel, so the alert routing is unchanged.");return}let l=new Set(i.map(pn)),u=(I)=>l.has(pn(I))||c.has(pn(I)),d=i.filter((I)=>!r.has(pn(I))),p=[...r].filter((I)=>a.has(I)&&!l.has(I));if(d.length===0&&p.length===0)return;let m=(I)=>({channel:I.channel,destinationKey:I.destinationKey});if(n.length===0){let I=null;if(await le({label:oe({what:"Saving your alert channels"}),json:e.json,work:()=>Eu({client:e.client,json:e.json,reportFailure:(B)=>{I=B},destinations:i.map(m),notificationTypes:[...hS],includeDescendants:!1,condition:{}})})===null&&I!==null)Ue(I);return}let b=[];for(let[I,C]of n.entries()){let B=C.destinations.filter(u),V=I===0?[...B,...d]:B;if(V.length===C.destinations.length&&d.length===0)continue;if(V.length===C.destinations.length&&V.every((ee,Z)=>ee===C.destinations[Z]))continue;b.push(V.length===0?{kind:"delete",rule:C}:{kind:"update",rule:C,next:V})}b.sort((I,C)=>I.kind===C.kind?0:I.kind==="update"?-1:1);let y=0;for(let I of b){let C=await le({label:oe({what:"Applying your alert channels"}),json:e.json,work:()=>I.kind==="delete"?e.client.notificationDeliveryRules.delete(I.rule.id):e.client.notificationDeliveryRules.update({ruleId:I.rule.id,destinations:I.next.map(m),notificationTypes:I.rule.notificationTypes,includeDescendants:I.rule.includeDescendants,condition:I.rule.condition})});if(!C.success){Fe(`Couldn't finish updating the alert channels (${C.error}). ${y} of ${b.length} ${b.length===1?"change":"changes"} saved; the remaining channels are still routed as before. Come back to this step to finish.`);return}y+=1}},OV=async(e,t)=>{let n=new Set,r=await Ej(e,t,n);if(r===null||r==="back"||r==="keep"||r==="quit")return r;return{selected:r,offered:n}},zj={run:CV,doneNote:async(e)=>{let t=await e.client.notificationDeliveryRules.list();if(!t.success)return null;let n=new Set(Lj(t.value.rules).flatMap((r)=>r.destinations.map(pn))).size;return`${n} ${Bv(n,"channel")}`},revisit:PV,ownsBackAffordance:!0,instructions:()=>[{command:"sazabi notifications delivery-rules create --destination <channel:key> --notification-type issue_triggered",description:"Create the first alert delivery rule"}]};H();import*as Dj from"node:fs";import*as $j from"node:path";var xV=(e)=>{let t=!1;for(let n of e.split(`
|
|
226
|
-
`)){let r=n.trim();if(r.startsWith("[")){t=/^\[\s*remote\s+"origin"\s*\]$/.test(r);continue}if(!t)continue;let o=r.match(/^url\s*=\s*(.+)$/);if(o?.[1])return o[1].trim()}return null},AV=(e)=>{let t,n,r=e.match(/^[\w.-]+@([\w.-]+):(.+)$/);if(r)t=r[1],n=r[2];else try{let s=new URL(e);t=s.hostname,n=s.pathname}catch{return null}if(!t||!n)return null;let o=n.replace(/\.git$/,"").split("/").filter((s)=>s.length>0),i=o.at(-1)??null,a=o.length>=2?o.at(-2)??null:null;return{host:t.toLowerCase(),owner:a,name:i,fullName:a&&i?`${a}/${i}`:null}},Bu=(e)=>{try{let t=$j.join(e,".git","config"),n=Dj.readFileSync(t,"utf-8"),r=xV(n);if(!r)return null;return AV(r)}catch{return null}};var Gu={githubApp:0,personal:1,integration:2},Nj=(e)=>{let t=new Map;for(let n of e){let r=t.get(n.id);if(!r){t.set(n.id,{repo:n,sourceLabels:[n.sourceLabel]});continue}if(!r.sourceLabels.includes(n.sourceLabel))r.sourceLabels.push(n.sourceLabel);let o=r.repo.linked||n.linked;if(Gu[n.source]<Gu[r.repo.source])r.repo=n;if(o!==r.repo.linked)r.repo={...r.repo,linked:o}}return[...t.values()]},TV=(e)=>{let t=e.provider==="bitbucket"?"Bitbucket":"GitHub";if(e.source==="githubApp")return`GitHub App: ${e.sourceLabel}`;if(e.source==="personal")return`Your ${t} account: ${e.sourceLabel}`;return`${t} integration: ${e.sourceLabel}`},_V=(e)=>[...e].sort((t,n)=>Gu[t.repo.source]-Gu[n.repo.source]||t.repo.sourceLabel.localeCompare(n.repo.sourceLabel)||t.repo.fullName.localeCompare(n.repo.fullName)),jV=(e)=>e===1?"repository":"repositories",RV=(e,t)=>[..._V(e).map(({repo:n,sourceLabels:r})=>({label:r.length>1?`${n.fullName} (via ${r.join(", ")})`:n.fullName,value:n.accessSourceId,hint:n.isPrivate?"private":"public",group:TV(n),preselected:t(n)})),Ql(),eu()],Uj=async(e,t)=>{let n=await e.prompts.multiselect({message:"Select the repositories to link for code search",itemNoun:"repositories",requireExplicitSelection:t.requireExplicitSelection,choices:RV(t.rows,t.preselected)});if(n.includes(oi))return"quit";if(n.includes(ni))return"back";return n.filter((r)=>typeof r==="string")},EV=async(e)=>{let t=gt(await le({label:oe({what:"Loading your repositories"}),json:e.json,work:()=>e.client.repos.list()}),"Couldn't list repositories. Try this card again");if(t===null)return await Pi(e);let n=Nj(t.repos).filter(({repo:s})=>!s.linked);if(n.length===0){if(t.repos.length>0)return N("Every available repository is already linked."),await ir(e);if(e.snapshot.state?.githubAppSkipped)return N(`No repositories are available. The GitHub App install was skipped, so none can appear. Run 'sazabi onboarding start' and choose ${Cn} to reopen the Install GitHub App step, or connect your personal GitHub account with 'sazabi connected-accounts connect github'.`),await ir(e);return N("No repositories are available yet. Check the forge connection."),await ir(e)}let r=Bu(process.cwd()),o=r?.fullName?r.fullName.toLowerCase():null,i=await Uj(e,{rows:n,preselected:(s)=>o!==null&&s.fullName.toLowerCase()===o});if(i==="back")return"back";if(i==="quit")return"hold";if(i.length===0){N("Nothing selected. No repositories linked.");return}let a=await le({label:oe({what:"Linking repositories"}),json:e.json,work:()=>e.client.repos.add({accessSourceIds:i})});if(gt(a,"Couldn't link the repositories")===null)return},LV=async(e)=>{let t=gt(await le({label:oe({what:"Loading your repositories"}),json:e.json,work:()=>e.client.repos.list()}),"Couldn't list repositories. Try this card again");if(t===null)return await Pi(e);let n=Nj(t.repos);if(n.length===0)return N("No repositories are available yet. Check the forge connection."),await ir(e);let r=await Uj(e,{rows:n,preselected:(c)=>c.linked,requireExplicitSelection:!0});if(r==="back")return"back";if(r==="quit")return"hold";let o=new Set(r);if(o.size===0){N("No repositories selected. Code search needs at least one, so the linked repositories are unchanged.");return}let i=n.filter(({repo:c})=>!c.linked&&o.has(c.accessSourceId)).map(({repo:c})=>c.accessSourceId),a=n.filter(({repo:c})=>c.linked&&!o.has(c.accessSourceId)).map(({repo:c})=>c);if(i.length===0&&a.length===0)return;let s=await le({label:oe({what:"Applying your repository selection"}),json:e.json,work:async()=>{if(i.length>0){if(!(await e.client.repos.add({accessSourceIds:i})).success)return{failure:"Couldn't link the repositories"}}for(let c of a)if(!(await e.client.repos.remove({id:c.id})).success)return{failure:`Couldn't unlink ${c.fullName}`};return{failure:null}}});if(s.failure!==null){Ue(`${s.failure}. Try this card again.`);return}},Mj={run:EV,revisit:LV,ownsBackAffordance:!0,doneNote:async(e)=>{let t=await e.client.repos.list();if(!t.success)return null;let n=new Set(t.value.repos.filter((r)=>r.linked).map((r)=>r.id)).size;return`${n} ${jV(n)}`},instructions:()=>[{command:"sazabi repos list",description:"Available repositories with linked status"},{command:"sazabi repos add --access-source-id <id>",description:"Link a repository for code search"}]};var Fj={run:async(e)=>{let t=!e.json&&ke()?an():null;try{let n=await mi({client:e.client,provider:"github",projectId:e.projectId,json:e.json,webAppUrl:e.webAppUrl,cancellation:t??void 0,reportFailure:Ue,announceCompletion:!1});if(t?.requested()){Yt("Cancelled. The GitHub App is not installed.");return}}finally{t?.dispose()}},instructions:()=>[{command:"sazabi integrations connect github",description:"Install the Sazabi GitHub App via the browser flow"}]};var Bj=async(e)=>{let t=await e.client.connectedAccounts.list();if(!t.success)return null;return t.value.accounts.some((n)=>n.provider==="github"&&!n.needsReconnect)},Gj={run:async(e)=>{let t=await le({label:oe({what:"Checking your GitHub account"}),json:e.json,work:()=>Bj(e)});if(t){mt("Your GitHub account is already connected");return}if(t===null){Ue("Couldn't list connected accounts. Try this card again.");return}let n=!e.json&&ke()?an():null;try{let r=await uv({client:e.client,provider:"github",json:e.json,cancellation:n??void 0,announceCompletion:!1});if(n?.requested()){Yt("Cancelled. Your GitHub account is not connected.");return}if(!r.ok)Ue(r.message)}finally{n?.dispose()}},doneNote:async(e)=>await Bj(e)===!1?"via teammate":null,instructions:()=>[{command:"sazabi connected-accounts connect github",description:"Connect your personal GitHub account for code search"}]};H();Qr();H();Qe();var ys=(e)=>{let t=Oe();if(!t.success)return!1;let n=dt(t.value);if(!n.success)return!1;let r=pt(t.value,{...e,...Zt(n.value)});if(!r.success)return!1;return Ne(r.value).success},bs=(e,t)=>{Fe(`${e}, but saving it to the CLI profile failed. Run '${t}' to bind it, or re-run onboarding.`)};var zV=async(e,t)=>{let n=t.map((c)=>c.organizationName),r=`${e.webAppUrl}/onboarding`;N(n.length===1?`You've been invited to ${n[0]}. Accept the invitation in the dashboard, then press Enter:`:`You've been invited to ${n.slice(0,-1).join(", ")} and ${n.at(-1)}. Accept an invitation in the dashboard, then press Enter:`),Nt(r),tt(r),await e.prompts.waitForEnter("Press Enter once you've accepted...");let o=gt(await le({label:oe({what:"Looking for the organization you joined"}),json:e.json,work:()=>e.client.organizations.list()}),"Couldn't list your organizations. Try this step again");if(o===null)return;let i=new Set(t.map((c)=>c.organizationId)),a=o.organizations.find((c)=>i.has(c.id));if(!a){Ue("The invitation hasn't been accepted yet. Accept it in the dashboard, then run 'sazabi onboarding continue'.");return}if(!ys({activeOrganizationId:a.id,organizationName:a.name,activeProjectId:void 0}))bs(`You joined ${a.name}`,`sazabi organizations use ${a.id}`)},Kj={id:"create_org",title:"Create organization",doneNote:(e)=>e.profile.organizationName??null,check:async(e)=>{if(e.organizationId)return{state:"complete",detectedFrom:"local"};return{state:"incomplete",reason:"No active organization. Create one, or accept a pending invitation."}},run:async(e)=>{go();let t=e.snapshot.state?.pendingInvitations??[];if(t.length>0)return await zV(e,t);let r=Bu(process.cwd())?.owner??void 0;for(;;){let o=await e.prompts.text({message:"Name your organization",initial:r,placeholder:r?void 0:"e.g. Acme Corp"});if(!o){N("No organization name entered.");return}let i=await le({label:oe({what:"Creating your organization"}),json:e.json,work:()=>e.client.organizations.create(o)});if(!i.success){let c=fx(i);if(c.length===0){gt(i,"Couldn't create the organization. Try again");return}let l=c.map((u)=>u.replace(/\.$/,"")).join(". ");Ue(`Couldn't create the organization. ${l}. Enter a different name.`),r=o;continue}let a=i.value;if(!ys({activeOrganizationId:a.organization.id,organizationName:a.organization.name,activeProjectId:void 0}))bs(`Organization ${a.organization.name} was created`,`sazabi organizations use ${a.organization.id}`);return}},instructions:()=>[{command:"sazabi organizations create --name <name>",description:"Create an organization"},{command:"sazabi organizations use <organization-id>",description:"Set the active organization"}]};H();wn();var vs="us-west-2",DV=new Set(Yr.options),Wj=async(e)=>{try{let t=await fetch(new URL("/api/regions",e).toString());if(!t.ok)return[];let n=await t.json();if(!Array.isArray(n))return[];return n.flatMap((r)=>{if(typeof r?.regionCode!=="string"||!DV.has(r.regionCode))return[];return[{regionCode:r.regionCode,displayLabel:typeof r.displayLabel==="string"&&r.displayLabel.length>0?r.displayLabel:r.regionCode}]})}catch{return[]}},qj=(e)=>{switch(e.split("-")[0]){case"us":case"ca":case"mx":case"sa":return"Americas";case"eu":return"Europe";case"ap":return"Asia Pacific";default:return"Other regions"}},Vj=(e)=>{let t=[...e.filter((r)=>r.regionCode===vs),...e.filter((r)=>r.regionCode!==vs)];return[...new Set(t.map((r)=>qj(r.regionCode)))].flatMap((r)=>t.filter((o)=>qj(o.regionCode)===r).map((o)=>({label:o.displayLabel,value:o.regionCode,hint:o.regionCode,preselected:o.regionCode===vs,group:r})))};var $V=async(e)=>{let t=await le({label:oe({what:"Loading regions"}),json:e.json,work:()=>Wj(e.platformApiBaseUrl)});if(t.length===0){N(`Couldn't load the region list. Using the default region (${vs}).`);return}return e.prompts.select({message:"Choose the region for your Sazabi backend",choices:Vj(t)})},Hj=(e,t,n)=>{let r=ys({activeOrganizationId:e,activeProjectId:t});if(!r)bs(n,`sazabi projects use ${t}`);return r},Zj={id:"create_project",title:"Create project",doneNote:async(e)=>{if(!e.projectId)return null;let t=await e.client.projects.get(e.projectId);if(!t.success)return null;let{name:n,region:r}=t.value.project;return`${n}, ${r}`},check:async(e)=>{if(e.organizationId&&e.projectId)return{state:"complete",detectedFrom:"local"};if(!e.organizationId)return{state:"incomplete",reason:"No active organization. Complete the organization step first."};return{state:"incomplete",reason:e.snapshot.state?.projectId?"No active project. The organization's project isn't bound to this CLI profile yet.":"No active project. Choose a region to create one."}},run:async(e)=>{let t=e.organizationId;if(!t){N("No active organization. Run 'sazabi onboarding continue' to set one up first.");return}let n=e.snapshot.state?.projectId;if(n){Hj(t,n,"The organization's project was found");return}go(),ce("Configure your project");let r=await $V(e),o=gt(await le({label:oe({what:"Setting up your project"}),json:e.json,work:()=>e.client.onboarding.ensureDefaultProject({organizationId:t,...r?{region:r}:{}})}),"Couldn't set up the project. Try this step again");if(o===null)return;if(!o.created)N("Your organization already has a project, so no new one was created.");return Hj(t,o.project.id,o.created?`Project ${o.project.name} was created`:"The organization's project was found"),o.created?"created":void 0},instructions:()=>[{command:"sazabi onboarding continue",description:"Create the project (choose a region), or bind the organization's existing project"},{command:"sazabi projects create --name <name>",description:"Create a project with a name of your own instead"},{command:"sazabi projects use <project-id>",description:"Set the active project"}]};var NV=["slack","teams"],UV=async(e)=>{let t=await e.client.integrations.listConnections();if(!t.success)return!1;return t.value.connections.some((n)=>NV.includes(n.provider)&&n.isActive)},Jj={run:async(e)=>{if(await le({label:oe({what:"Checking your chat connection"}),json:e.json,work:()=>UV(e)})){mt("A chat app is already connected");return}let n=!e.json&&ke()?an():null;try{if(await mi({client:e.client,provider:"slack",projectId:e.projectId,json:e.json,webAppUrl:e.webAppUrl,cancellation:n??void 0,reportFailure:Ue,announceCompletion:!1}),n?.requested()){Yt("Cancelled. Slack is not connected.");return}}finally{n?.dispose()}},instructions:()=>[{command:"sazabi integrations connect slack",description:"Connect Slack via the browser flow"}]};var Ku={id:"sign_in",title:"Sign in",listed:!1,check:async(e)=>{let t=await le({label:oe({what:"Checking your session"}),json:e.json,work:()=>e.client.me()});if(!t.success)return{state:"incomplete",reason:!e.hasCredentials||t.statusCode===401?"Not signed in. Run 'sazabi auth sign-in' to authenticate.":`Couldn't check your session (${t.error}). Try again in a moment.`};if(t.value.credentialType!=="user")return{state:"incomplete",reason:"Signed in with a secret key. Onboarding needs a personal user token (billing and finishing onboarding are user-only). Run 'sazabi auth sign-in'."};return{state:"complete",detectedFrom:"server"}},run:async(e)=>{go();for(;;){if(await e.prompts.select({message:"Welcome to Sazabi",choices:[{label:"Create a Sazabi account",value:"signup",hint:"Opens the sign-up page in your browser"},rr]})==="quit")return"quit";let n=!e.json&&ke()?an():null,r=n?{cancellation:n}:{},o=null;try{o=await Wo({json:e.json,apiBaseUrl:e.apiBaseUrl,authBaseUrl:e.platformApiBaseUrl,reportFailure:Ue,...r})}finally{n?.dispose()}if(n?.requested()){Yt(tu);continue}if(o===null)continue;return}},instructions:()=>[{command:"sazabi auth sign-in",description:"Sign in with a personal user token via the browser"}]};H();H();var Yj=60,MV={topLeft:"┌",topRight:"┐",bottomLeft:"└",bottomRight:"┘",leftTee:"├",rightTee:"┤",horizontal:"─",vertical:"│",marker:"●"},FV={topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",leftTee:"+",rightTee:"+",horizontal:"-",vertical:"|",marker:"*"},BV=" · ",GV=", ",KV=(e=process.env)=>{let t=e.LC_ALL??e.LC_CTYPE??e.LANG??"";if(t==="")return!0;return/utf-?8/i.test(t)},qV=(e)=>{switch(e){case"critical":case"high":return _.error(e);case"medium":return _.warning(e);case"low":return _.info(e);default:return e}},Xj=(e,t)=>{let n=[],r="";for(let o of e.split(/\s+/).filter((i)=>i!=="")){if(r==="")r=o;else if(r.length+1+o.length<=t)r=`${r} ${o}`;else n.push(r),r=o;while(r.length>t)n.push(r.slice(0,t)),r=r.slice(t)}if(r!=="")n.push(r);return n.length>0?n:[""]},Qj=(e,t,n)=>`${e}${" ".repeat(Math.max(0,n-t))}`,WV=(e)=>{let t=e.ascii??!KV(),n=t?FV:MV,r=t?GV:BV,o=Math.min(Yj,process.stdout.columns||Yj),i=Math.max(32,e.width??o),s=e.status==="resolved"?_.success:_.error,c=ms[e.status],l=i-4,u=(Z,re)=>s(Z+n.horizontal.repeat(i-2)+re),d=(Z,re)=>`${s(n.vertical)} ${Qj(Z,re,l)} ${s(n.vertical)}`,p=[u(n.topLeft,n.topRight)],m=`${n.marker} ${jt.name}`,b=`${s(n.marker)} ${_.bold(jt.name)}`,y=[jt.component,jt.severity,c].join(r),I=[_.muted(jt.component),qV(jt.severity),s(c)].join(_.muted(r));if(m.length+2+y.length<=l){let Z=l-m.length-y.length;p.push(d(`${b}${" ".repeat(Z)}${I}`,m.length+Z+y.length))}else{p.push(d(b,m.length));for(let Z of Xj(y,l-2))p.push(d(_.muted(` ${Z}`),Z.length+2))}p.push(u(n.leftTee,n.rightTee));let C=l-4,B=(Z,re)=>d(_.muted(Z+n.horizontal.repeat(l-2)+re),l),V=(Z,re)=>d(`${_.muted(n.vertical)} ${Qj(Z,re,C)} ${_.muted(n.vertical)}`,C+4);p.push(B(n.topLeft,n.topRight)),p.push(V(_.muted(Lu.toUpperCase()),Lu.length));for(let Z of Xj(jt.description,C))p.push(V(Z,Z.length));p.push(B(n.bottomLeft,n.bottomRight));let ee=oS();return p.push(d(_.muted(ee),ee.length)),p.push(u(n.bottomLeft,n.bottomRight)),p},qu=(e)=>{for(let t of WV({status:e}))console.log(t)};var eR=(e)=>({name:jt.name,component:jt.component,severity:jt.severity,status:ms[e].toLowerCase(),description:jt.description,occurredAt:nS().toISOString()}),tR=()=>{ce(rS),N(eS)},nR=async(e)=>gt(await le({label:oe({what:"Resolving the issue"}),json:e.json,work:()=>e.client.onboarding.completeSampleIssue(e.projectId?{projectId:e.projectId}:void 0)}),"Couldn't resolve the test issue. Try this card again")!==null,oR={run:async(e)=>{if(e.json){j(eR("open")),await nR(e);return}if(tR(),qu("open"),ke()){if(await e.prompts.select({message:"Resolve this issue to continue",choices:[{label:"Resolve",value:"resolve",preselected:!0},{label:mo,value:"quit"}]})==="quit")return"hold"}if(!await nR(e))return"hold";if(qu("resolved"),ke()){if(await e.prompts.select({message:"Continue",choices:[{label:"Continue",value:"continue",preselected:!0},{label:mo,value:"quit"}]})==="quit")return"hold"}},ownsBackAffordance:!0,renderRevisit:async(e)=>{if(e.json){j(eR("resolved"));return}tR(),qu("resolved")},instructions:()=>[{command:"sazabi onboarding continue",description:"Resolve the test issue to complete this step"}]};var fS=[Ku,Kj],Ss=Zj,VV={set_up_billing:Cj,connect_github_account:Gj,install_github_app:Fj,configure_code_search:Mj,install_slack_app:Jj,configure_slack_alerts:zj,trigger_sample_issue:oR},Oi=(e)=>VV[e],Wu={run:async(e,t)=>{let n=Oi(e.id);if(!n){N(`This step isn't available in this CLI version. Finish it in the dashboard: ${t.webAppUrl}/onboarding`);return}return await n.run(t)},instructions:(e,t)=>{let n=Oi(e.id);if(n)return n.instructions(t);return[{url:`${t.webAppUrl}/onboarding`,description:e.instructions}]},doneNote:async(e,t)=>await Oi(e.id)?.doneNote?.(t)??null,renderRevisit:async(e,t)=>{await Oi(e.id)?.renderRevisit?.(t)},ownsBackAffordance:(e)=>Oi(e.id)?.ownsBackAffordance??!1,revisit:(e)=>Oi(e.id)?.revisit??null};var bS={...O,"project-id":{type:"string"},"organization-id":{type:"string"}},Vu={...x,"project-id":{type:"string",description:"Override active project ID"},"organization-id":{type:"string",description:"Override active organization ID"}},vS=(e)=>({token:e.token,projectId:e["project-id"],organizationId:e["organization-id"],apiBaseUrl:e["api-base-url"],json:Boolean(e.json)}),rR=async(e,t)=>{let n=await le({label:oe({what:"Loading your setup"}),json:Boolean(e.json),work:()=>Uu(e)});if(t==="continue"&&!e.json&&ke()){let o=await Zn(n,Ku);if(o.state==="incomplete")return g(n.hasCredentials?o.reason:`${o.reason} To create a new account instead, run 'sazabi start'.`)}{let o=await le({label:oe({what:"Checking your project"}),json:Boolean(e.json),work:()=>lS(n)});if(!o.success){if(e.json)return h(o.error);return g(o.error)}}let r=await wj({preamble:fS,projectGate:Ss,interpreter:Wu,json:Boolean(e.json),buildContext:()=>Uu(e),initialContext:n});if(r!==0)process.exit(r)},HV=async(e)=>{if(e.json||!ke())return!0;if(e.token?.trim()||process.env.SAZABI_TOKEN?.trim())return!0;if(!f(vt(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",!1).token?.trim())return!0;if(await qo({message:"You're already signed in. Sign out and create a new account?",choices:[{label:"Yes, sign out",value:"sign-out"},{label:"No",value:"stay"}]})==="stay")return N("Run 'sazabi onboarding continue' to keep setting up your current account."),!1;return Vb({json:!1}),!0},ZV=async(e)=>{let{values:t}=S(e,bS),n=vS(t);if(!await HV(n))return;await rR(n,"start")},JV=async(e)=>{let{values:t}=S(e,bS);await rR(vS(t),"continue")},YV=(e)=>{switch(e.state){case"done":return"complete";case"pending":return"incomplete";case"skipped":return"skipped";case"not-applicable":return"not applicable";case"unavailable":return"unavailable"}},XV=(e,t)=>({id:e.card.id,label:e.card.label,skippable:Hn(e.card.id),status:YV(e.status),...e.status.state==="unavailable"?{skippedDependency:e.status.dependency}:{},actions:Wu.instructions(e.card,t)}),Is=[...fS.map((e)=>({step:e,position:"pre-flow"})),{step:Ss,position:"gate-line"},{step:dS,position:"post-flow"}],QV=(e,t,n)=>({id:e.id,label:e.title,status:t.state,...t.state==="incomplete"?{reason:t.reason}:{},actions:e.instructions(n)}),eH=async(e)=>{let{values:t}=S(e,bS),n=vS(t),r=Boolean(n.json),o=await le({label:oe({what:"Loading your setup"}),json:r,work:()=>Uu(n)});{let y=await le({label:oe({what:"Checking your project"}),json:r,work:()=>lS(o)});if(!y.success){if(r)return h(y.error);return g(y.error)}}let i=Ij(o);if(i.kind==="read-error"){let y=`Couldn't load the onboarding state (${i.error}). Try again in a moment.`;if(r)return h(y);return g(y)}let a=i.rows,s="Project-scoped steps are hidden until a project is set. Run 'sazabi onboarding continue' to set one up.",c=new Map,l=(y)=>c.get(y.id)??{state:"incomplete",reason:"Status unavailable."},u=new Map,d=new Map;if(await Promise.all(Is.map(async({step:y})=>{c.set(y.id,await Zn(o,y))})),!r){let y=[...Is.map(({step:I})=>I),Ss].filter((I)=>l(I).state==="complete");await le({label:oe({what:"Loading your setup"}),json:r,work:()=>Promise.all([...y.map((I)=>ki(I,o).then((C)=>u.set(I.id,C)).catch(()=>u.set(I.id,null))),...a.filter((I)=>I.status.state==="done").map((I)=>Promise.resolve(Wu.doneNote?.(I.card,o)).then((C)=>d.set(I.card.id,C??null)).catch(()=>d.set(I.card.id,null)))])})}if(r){j({gates:Is.map(({step:y})=>QV(y,l(y),o)),onboarding:a.map((y)=>XV(y,o)),...i.kind==="org-only"?{note:s}:{}});return}if(!o.hasCredentials)N("Not signed in. Completion state is unavailable. Run 'sazabi auth sign-in' first.");let p=new Map(a.map((y)=>[y.card.id,y])),m=(y)=>{let I=l(y),C=Ii({step:y,status:I,detail:u.get(y.id)??null});if(C!==null)console.log(C)},b=(y)=>{let I=y.status.state==="done"?d.get(y.card.id)??null:null,C=or({card:y.card,status:y.status,detail:I});if(C!==null)console.log(C)};ce("Onboarding");for(let{step:y,position:I}of Is)if(I==="pre-flow")m(y);for(let y of Bt){if(y.kind==="gate"){m(Ss);continue}let I=p.get(y.id);if(I)b(I)}for(let{step:y,position:I}of Is)if(I==="post-flow")m(y);if(i.kind==="org-only")console.log(""),N(s)},SS=q("onboarding","Guided setup for a project from the terminal").withOptions(Vu).withSubcommands({start:v("start","Start onboarding a new account (offers to sign out first when signed in)",ZV).withOptions(Vu).withExamples(["sazabi onboarding start # Walk every step, showing completed ones","sazabi onboarding start --json # Emit the next actionable step as JSON"]).build(),continue:v("continue","Run the onboarding flow from the first incomplete step",JV).withOptions(Vu).withExamples(["sazabi onboarding continue # Resume at the first incomplete step","sazabi onboarding continue --json # Emit the next actionable step as JSON"]).build(),progress:v("progress","Read-only onboarding checklist",eH).withOptions(Vu).withExamples(["sazabi onboarding progress # Every step with its status","sazabi onboarding progress --json # Full checklist as JSON, with each step's actions"]).build()}).withExamples(["sazabi onboarding continue # Resume at the first incomplete step","sazabi onboarding start # Walk every step from the top","sazabi onboarding progress # Read-only checklist"]).build(),yS=SS.subcommands?.start;if(!yS)throw Error('onboarding subcommand "start" is missing');var iR={...yS,name:"start",examples:[...(yS.examples??[]).map((e)=>e.replace("sazabi onboarding start","sazabi start")),"sazabi onboarding start # Canonical form; sazabi start is its permanent alias"]};H();se();te();Qe();var aR={id:{label:"ID",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},slug:{label:"Slug",type:{kind:"string"}},role:{label:"Role",type:{kind:"nullable-string"}}},tH={schema:aR,columns:["id","name","slug","role"],header:"Organizations",emptyMessage:"No organizations found."},sR={layout:"field-list",schema:aR,fields:["id","name","slug","role"]},nH=async(e)=>{let t=A({tokenFlag:e.token,jsonMode:e.json}),n=T({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:e.json}),r=f(await n.organizations.list(),"Couldn't list organizations (check your token and try again)",e.json);D(tH,r.organizations,{json:e.json})},oH=async(e,t)=>{let n=A({tokenFlag:t.token,jsonMode:t.json}),r=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t.json),o=T({token:n.token,organizationId:e,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),i=f(await o.organizations.get(e),"Couldn't fetch organization (run 'sazabi organizations list' to see organization IDs)",t.json).organization,a=f(await o.projects.list({organizationId:e}),"Couldn't fetch organization projects (check the organization ID and try again)",t.json).projects,s=f(dt(r),"Couldn't resolve profile (run 'sazabi profiles list' to see available profiles)",t.json),c=s.activeProjectId&&a.some((p)=>p.id===s.activeProjectId)?s.activeProjectId:a[0]?.id,l=i.id!==s.activeOrganizationId,u=c!==s.activeProjectId,d=f(pt(r,{activeOrganizationId:i.id,organizationName:i.name,activeProjectId:c,...(l||u)&&Zt(s)}),"Failed to update profile",t.json);if(f(Ne(d),"Failed to persist active organization",t.json),t.json){j({organization:i,activeProjectId:f(dt(d),"Couldn't resolve profile (run 'sazabi profiles list' to see available profiles)",t.json).activeProjectId});return}z(`Active organization set to ${i.name}.`)},rH=async(e,t)=>{let n=A({tokenFlag:t.token,jsonMode:t.json}),r=T({token:n.token,organizationId:n.organizationId,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),{organization:o}=f(await r.organizations.create(e),"Failed to create organization",t.json);if(iH(o.id,o.name),t.json){j({organization:o});return}z(`Organization ${o.name} created.`),R(sR,{...o,role:"admin"},{json:t.json})},iH=(e,t)=>{let n=Oe();if(!n.success)return;let r=n.value,o=dt(r);if(!o.success)return;let i=pt(r,{activeOrganizationId:e,organizationName:t,activeProjectId:void 0,...Zt(o.value)});if(i.success)Ne(i.value)},aH=async(e,t)=>{let n=A({tokenFlag:t.token,organizationIdFlag:t.organizationId,jsonMode:t.json}),r=T({token:n.token,organizationId:n.organizationId,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),o=f(await r.organizations.rename(e,n.organizationId),"Failed to rename organization",t.json);sH(o.organization.id,o.organization.name),R(sR,o.organization,{json:t.json})},sH=(e,t)=>{let n=Oe();if(!n.success)return;let r=n.value,o=dt(r);if(!o.success)return;if(o.value.activeOrganizationId!==e)return;let i=pt(r,{organizationName:t});if(i.success)Ne(i.value)},cR=q("organizations","Manage organizations").withSubcommands({list:v("list","List organizations available to the current credential",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0});if(n.length>0){let r=n.join(", ");if(t.json)return h(`Unexpected arguments: ${r}. Run 'sazabi organizations -h' for usage.`);return g(`Unexpected arguments: ${r}. Run 'sazabi organizations -h' for usage.`)}await nH({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi organizations list # List available organizations"]).build(),create:v("create","Create an organization and make it the active one",async(e)=>{let{values:t}=S(e,{token:{type:"string"},name:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}}),n=t.name?.trim();if(!n){if(t.json)return h("--name is required.");return g("--name is required.")}await rH(n,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},name:{type:"string",description:"Organization display name (required)"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(['sazabi organizations create --name "Acme Corp" # Create an organization']).build(),use:v("use","Set the active organization for future commands",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Organization ID is required.");return g("Organization ID is required.")}await oH(r,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi organizations use org_123 # Set the active organization"]).build(),rename:v("rename","Rename the active organization",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},"organization-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Organization name is required.");return g("Organization name is required.")}if(n.length>1){let o=n.slice(1).join(", ");if(t.json)return h(`Unexpected arguments: ${o}. Run 'sazabi organizations -h' for usage.`);return g(`Unexpected arguments: ${o}. Run 'sazabi organizations -h' for usage.`)}await aH(r,{token:t.token,organizationId:t["organization-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(['sazabi organizations rename "Observed Platform" # Rename the active organization']).build()}).withExamples(["sazabi organizations list # List available organizations","sazabi organizations use org_123 # Set the active organization",'sazabi organizations rename "Observed Platform" # Rename the active organization']).build();H();te();Qe();var cH={name:{label:"Profile",type:{kind:"string"}},active:{label:"Active",type:{kind:"custom",render:(e)=>e?_.success("*"):"",serialize:(e)=>Boolean(e)}}},lH=(e)=>{let t=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",e.json),n=Object.keys(t.profiles).map((r)=>({name:r,active:r===t.activeProfile}));D({schema:cH,columns:["name","active"],header:"Profiles",emptyMessage:"No profiles configured."},n,{json:e.json})},uH=(e,t)=>{let n=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t.json);if(!n.profiles[e]){let r=`Profile '${e}' does not exist. Run 'sazabi profiles list' to see available profiles.`;if(t.json)h(r);g(r)}if(n.activeProfile=e,f(Ne(n),"Failed to write settings",t.json),t.json){j({activeProfile:e});return}z(`Active profile set to '${e}'.`)},dH=(e,t)=>{let n=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t.json);if(n.profiles[e]){let r=`Profile '${e}' already exists.`;if(t.json)h(r);g(r)}if(n.profiles[e]={},f(Ne(n),"Failed to write settings",t.json),t.json){j({created:e});return}z(`Profile '${e}' created.`)},pH=(e,t)=>{let n=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t.json);if(!n.profiles[e]){let r=`Profile '${e}' does not exist. Run 'sazabi profiles list' to see available profiles.`;if(t.json)h(r);g(r)}if(e===n.activeProfile){let r=`Cannot delete the active profile '${e}'. Switch to a different profile first with 'sazabi profiles use <name>'.`;if(t.json)h(r);g(r)}if(delete n.profiles[e],f(Ne(n),"Failed to write settings",t.json),t.json){j({deleted:e});return}z(`Profile '${e}' deleted.`)},lR=q("profiles","Manage named CLI profiles").withSubcommands({list:v("list","List all profiles",async(e)=>{let{values:t}=S(e,{json:{type:"boolean"}});lH({json:t.json})}).withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(["sazabi profiles list # List all profiles"]).build(),use:v("use","Set the active profile",async(e)=>{let{values:t,positionals:n}=S(e,{json:{type:"boolean"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Profile name is required. Usage: sazabi profiles use <name>");return g("Profile name is required. Usage: sazabi profiles use <name>")}uH(r,{json:t.json})}).withPositionalArgs("<name>").withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(["sazabi profiles use staging # Switch to staging profile"]).build(),create:v("create","Create a new empty profile",async(e)=>{let{values:t,positionals:n}=S(e,{json:{type:"boolean"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Profile name is required. Usage: sazabi profiles create <name>");return g("Profile name is required. Usage: sazabi profiles create <name>")}dH(r,{json:t.json})}).withPositionalArgs("<name>").withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(["sazabi profiles create staging # Create a new profile"]).build(),delete:v("delete","Delete a profile",async(e)=>{let{values:t,positionals:n}=S(e,{json:{type:"boolean"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Profile name is required. Usage: sazabi profiles delete <name>");return g("Profile name is required. Usage: sazabi profiles delete <name>")}pH(r,{json:t.json})}).withPositionalArgs("<name>").withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(["sazabi profiles delete staging # Delete a profile"]).build()}).withExamples(["sazabi profiles list # List all profiles","sazabi profiles use staging # Switch to staging profile","sazabi profiles create local # Create a new profile","sazabi profiles delete staging # Delete a profile"]).build();H();se();te();Qe();var mH={id:{label:"ID",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},region:{label:"Region",type:{kind:"string"}},active:{label:"Active",type:{kind:"custom",render:(e)=>e?_.success("*"):"",serialize:(e)=>e}},url:{label:"URL",type:{kind:"string"}}},gH={schema:mH,columns:["id","name","region","active","url"],header:"Projects",emptyMessage:"No projects found."},hH={id:{label:"ID",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},region:{label:"Region",type:{kind:"string"}},organizationId:{label:"Organization",type:{kind:"string"}}},fH={layout:"field-list",schema:hH,fields:["id","name","region","organizationId"],title:"Project"},yH=async(e)=>{let t=A({tokenFlag:e.token,organizationIdFlag:e.organizationId,jsonMode:e.json}),n=T({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:e.json}),r=f(await n.projects.create({name:e.name,...e.organizationId?{organizationId:e.organizationId}:{},...e.region?{region:e.region}:{}}),"Failed to create project",e.json);if(R(fH,{id:r.project.id,name:r.project.name,region:r.project.region,organizationId:r.project.organizationId},{json:e.json,contract:r.project}),!e.json)z(`Project ${r.project.name} created.`)},bH=async(e)=>{let t=A({tokenFlag:e.token,organizationIdFlag:e.organizationId,jsonMode:e.json}),n=T({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:e.json}),o=f(await n.projects.list({organizationId:t.organizationId}),"Couldn't list projects (check the active organization and try again)",e.json).projects.map((i)=>({...i,active:i.id===t.projectId,url:uo(i.id)}));D(gH,o,{json:e.json})},vH=async(e,t)=>{let n=A({tokenFlag:t.token,jsonMode:t.json}),r=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t.json),o=T({token:n.token,organizationId:n.organizationId,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),i=f(await o.projects.get(e),"Couldn't fetch project (run 'sazabi projects list' to see project IDs)",t.json).project,a=Ht(r),s=r.profiles[a],c=i.organizationId!==s?.activeOrganizationId,l=i.id!==s?.activeProjectId,u=f(pt(r,{activeOrganizationId:i.organizationId,activeProjectId:i.id,...c&&{organizationName:void 0},...(c||l)&&Zt(s)}),"Failed to update profile",t.json);if(f(Ne(u),"Failed to persist active project",t.json),t.json){j({project:i});return}z(`Active project set to ${i.name}.`)},uR=q("projects","Manage projects").withSubcommands({list:v("list","List projects in the active organization",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},"organization-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0});if(n.length>0){let r=n.join(", ");if(t.json)return h(`Unexpected arguments: ${r}. Run 'sazabi projects -h' for usage.`);return g(`Unexpected arguments: ${r}. Run 'sazabi projects -h' for usage.`)}await bH({token:t.token,organizationId:t["organization-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi projects list # List projects in the active organization"]).build(),use:v("use","Set the active project for future commands",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Project ID is required.");return g("Project ID is required.")}await vH(r,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi projects use 11111111-1111-4111-8111-111111111111 # Set the active project"]).build(),create:v("create","Create a new project in the active organization",async(e)=>{let{values:t,positionals:n}=S(e,{...O,name:{type:"string"},region:{type:"string"},"organization-id":{type:"string"}},{allowPositionals:!0});if(n.length>0){let r=n.join(", ");if(t.json)return h(`Unexpected arguments: ${r}. Run 'sazabi projects -h' for usage.`);return g(`Unexpected arguments: ${r}. Run 'sazabi projects -h' for usage.`)}if(!t.name){if(t.json)return h("--name is required.");return g("--name is required.")}await yH({name:t.name,region:t.region,organizationId:t["organization-id"],token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({...x,name:{type:"string",required:!0,description:"Project name (required)"},region:{type:"string",description:"AWS region for the project (defaults to us-west-2)"},"organization-id":{type:"string",description:"Override organization selection"}}).withExamples(['sazabi projects create --name "My Project" # Create a project in the active organization','sazabi projects create --name "EU App" --region eu-central-1 # Create in a specific region']).build()}).withExamples(["sazabi projects list # List projects in the active organization","sazabi projects use 11111111-1111-4111-8111-111111111111 # Set the active project",'sazabi projects create --name "My Project" # Create a project']).build();H();se();te();var SH={id:{label:"ID",type:{kind:"string"}},projectId:{label:"Project",type:{kind:"string"}},repositoryFullName:{label:"Repository",type:{kind:"string"}},githubPullRequestId:{label:"PR #",type:{kind:"number"}},title:{label:"Title",type:{kind:"nullable-string"}},url:{label:"URL",type:{kind:"nullable-string"}},status:{label:"Status",type:{kind:"nullable-string"}},reviewState:{label:"Review",type:{kind:"nullable-string"}},checksState:{label:"Checks",type:{kind:"nullable-string"}},requestedByUserId:{label:"Requested by",type:{kind:"nullable-string"}},githubAuthorLogin:{label:"GitHub author",type:{kind:"nullable-string"}},threadId:{label:"Thread",type:{kind:"nullable-string"}},runId:{label:"Run",type:{kind:"nullable-string"}},createdAt:{label:"Created",type:{kind:"date"}},mergedAt:{label:"Merged",type:{kind:"nullable-date"}},closedAt:{label:"Closed",type:{kind:"nullable-date"}}},IH=["id","projectId","repositoryFullName","githubPullRequestId","title","url","status","reviewState","checksState","requestedByUserId","githubAuthorLogin","threadId","runId","createdAt","mergedAt","closedAt"],kH={schema:SH,columns:["repositoryFullName","githubPullRequestId","title","status","createdAt"],jsonFields:IH,header:"Pull requests",emptyMessage:"No pull requests found."},wH=async(e)=>{let t=A({tokenFlag:e.token,jsonMode:e.json}),n=T({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:e.json}),r=f(await n.pullRequests.list({status:e.status,repositoryFullName:e.repository,requestedByUserId:e.requestedBy,limit:e.limit,cursor:e.cursor}),"Couldn't list pull requests (check the active project and try again)",e.json);D(kH,r.pullRequests,{json:e.json,nextCursor:r.nextCursor})},dR=q("pull-requests","List pull requests opened by Sazabi").withSubcommands({list:v("list","List pull requests Sazabi opened in the active project",async(e)=>{let{values:t}=S(e,{...O,status:{type:"string"},repository:{type:"string"},"requested-by":{type:"string"},mine:{type:"boolean"},limit:{type:"string"},cursor:{type:"string"}}),n=["open","merged","closed"];if(t.status&&!n.includes(t.status)){let i=`Invalid --status "${t.status}". Must be one of: ${n.join(", ")}.`;if(t.json)return h(i);return g(i)}let r=t.limit?Number(t.limit):void 0;if(r!==void 0&&(Number.isNaN(r)||r<1||r>100)){if(t.json)return h("Invalid --limit. Must be an integer between 1 and 100.");return g("Invalid --limit. Must be an integer between 1 and 100.")}let o=t.mine?"me":t["requested-by"];await wH({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],status:t.status,repository:t.repository,requestedBy:o,limit:r,cursor:t.cursor})}).withOptions({...x,status:{type:"string",description:"Filter by status: open, merged, or closed"},repository:{type:"string",description:"Filter by repository full name, for example owner/repo"},"requested-by":{type:"string",description:"Filter by the Sazabi user ID that requested the PR (or 'me')"},mine:{type:"boolean",description:"Only show pull requests you requested (requires user authentication)"},limit:{type:"string",description:"Maximum number of pull requests to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from a previous response"}}).withExamples(["sazabi pull-requests list # List PRs Sazabi opened in the active project","sazabi pull-requests list --status open --mine # Your open PRs","sazabi pull-requests list --repository sazabi/monorepo --json # PRs in one repo as JSON"]).build()}).withExamples(["sazabi pull-requests list # List PRs Sazabi opened","sazabi pull-requests list --status open --mine # Your open PRs","sazabi pull-requests list --repository owner/repo # PRs in one repo"]).build();H();se();te();var CH={priority:{label:"#",type:{kind:"number"}},kind:{label:"Kind",type:{kind:"string"}},targetId:{label:"Target",type:{kind:"string"}},status:{label:"Status",type:{kind:"custom",render:(e)=>e==="connected"?_.success("connected"):_.info("recommended"),serialize:(e)=>e}},roiScore:{label:"ROI",type:{kind:"number"}},components:{label:"Because you run",type:{kind:"custom",render:(e)=>{let t=e.map((n)=>n.name);return t.length>0?t.join(", "):_.muted("—")},serialize:(e)=>e}}},PH={schema:CH,columns:["priority","kind","targetId","status","roiScore","components"],header:"Recommendations",emptyMessage:"No recommendations found."},pR=["log_source","mcp_connector","sandbox_cli","integration"],mR=["connected","recommended"],OH=async(e)=>{if(e.kind&&!pR.includes(e.kind)){let i=`Invalid --kind: ${e.kind}. Expected one of: ${pR.join(", ")}.`;if(e.json)return h(i);return g(i)}if(e.status&&!mR.includes(e.status)){let i=`Invalid --status: ${e.status}. Expected one of: ${mR.join(", ")}.`;if(e.json)return h(i);return g(i)}let t=A({tokenFlag:e.token,projectIdFlag:e.projectId,organizationIdFlag:e.organizationId,jsonMode:e.json}),n=T({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:e.json}),o=f(await n.recommendations.list(),"Couldn't list recommendations (check the active project and try again)",e.json).recommendations.filter((i)=>(!e.kind||i.kind===e.kind)&&(!e.status||i.status===e.status));D(PH,o,{json:e.json})},xH={...O,"project-id":{type:"string"},"organization-id":{type:"string"},kind:{type:"string"},status:{type:"string"}},AH={...x,"project-id":{type:"string",description:"Override active project ID"},"organization-id":{type:"string",description:"Override active organization ID"},kind:{type:"string",description:"Filter by kind (log_source, mcp_connector, sandbox_cli, integration)"},status:{type:"string",description:"Filter by status (connected, recommended)"}},gR=q("recommendations","View setup recommendations for a project").withSubcommands({list:v("list","List setup recommendations for the active project",async(e)=>{let{values:t}=S(e,xH);await OH({token:t.token,projectId:t["project-id"],organizationId:t["organization-id"],apiBaseUrl:t["api-base-url"],json:t.json,kind:t.kind,status:t.status})}).withOptions(AH).withExamples(["sazabi recommendations list # List all recommendations","sazabi recommendations list --status recommended # Only not-yet-connected items","sazabi recommendations list --kind log_source # Only log sources","sazabi recommendations list --json # Output as JSON"]).build()}).withExamples(["sazabi recommendations list # List all recommendations","sazabi recommendations list --json # Output as JSON"]).build();H();se();te();var TH={id:{label:"ID",type:{kind:"id"}},accessSourceId:{label:"Access source",type:{kind:"string"}},fullName:{label:"Repository",type:{kind:"string"}},sourceLabel:{label:"Source",type:{kind:"string"}},source:{label:"Source kind",type:{kind:"string"}},provider:{label:"Provider",type:{kind:"string"}},linked:{label:"Linked",type:{kind:"boolean"}},defaultBranch:{label:"Default branch",type:{kind:"nullable-string"}},isPrivate:{label:"Private",type:{kind:"boolean"}}},hR={schema:TH,columns:["id","fullName","sourceLabel","provider","linked"],jsonFields:["id","accessSourceId","fullName","source","sourceLabel","provider","linked","defaultBranch","isPrivate"],header:"Repositories",emptyMessage:"No repositories available. Connect a forge with 'sazabi integrations connect github' first."},_H={...hR,header:"Linked repositories"},kS={...O,"project-id":{type:"string"}},IS={...x,"project-id":{type:"string",description:"Override active project ID"}},wS=(e)=>{let t=e.json,n=A({tokenFlag:e.token,projectIdFlag:e["project-id"],jsonMode:t});return{client:T({token:n.token,organizationId:n.organizationId,projectId:n.projectId,apiBaseUrlFlag:e["api-base-url"],jsonMode:t}),json:t}},jH=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,RH=async(e)=>{let{name:t,repos:n,json:r}=e,o=n.filter((s)=>s.fullName.toLowerCase()===t.toLowerCase());if(o.length===0){let s=n.filter((u)=>u.fullName.toLowerCase().includes(t.toLowerCase())).slice(0,5).map((u)=>u.fullName),c=s.length>0?` Did you mean: ${s.join(", ")}?`:"",l=`Couldn't find repository "${t}". Run 'sazabi repos list' to see available repositories.${c}`;if(r)return h(l);return g(l)}if(o.length===1){let s=o[0];if(!s)return g("Unreachable");return s.accessSourceId}if(!r&&ke())return qo({message:`"${o[0]?.fullName}" is available through several sources. Link via which?`,choices:o.map((s)=>({label:`${s.fullName} (${s.sourceLabel})`,value:s.accessSourceId}))});let i=o.map((s)=>`${s.accessSourceId} (${s.sourceLabel})`).join(", "),a=`"${t}" is available through several sources. Pass --access-source-id with one of: ${i}.`;if(r)return h(a);return g(a)},EH=(e)=>{if(Array.isArray(e))return e.filter((t)=>typeof t==="string");return typeof e==="string"?[e]:[]},LH=async(e)=>{let{values:t}=S(e,kS),{client:n,json:r}=wS(t),{repos:o}=f(await n.repos.list(),"Couldn't list repositories (check the active project and try again)",r);D(hR,o,{json:r})},zH=async(e)=>{let{values:t,positionals:n}=S(e,{...kS,"access-source-id":{type:"string",multiple:!0}},{allowPositionals:!0}),r=t.json,o=EH(t["access-source-id"]);if(o.length===0&&n.length===0){if(r)return h("Provide repositories to link: pass owner/name (from 'sazabi repos list') or --access-source-id.");return g("Provide repositories to link: pass owner/name (from 'sazabi repos list') or --access-source-id.")}let{client:i}=wS(t);if(n.length>0){let{repos:s}=f(await i.repos.list(),"Couldn't list repositories (check the active project and try again)",r);for(let c of n)o.push(await RH({name:c,repos:s,json:r}))}let{repos:a}=f(await i.repos.add({accessSourceIds:o}),"Failed to link repositories",r);if(!r)z("Repositories linked.");D(_H,a,{json:r})},DH=async(e)=>{let{values:t,positionals:n}=S(e,kS,{allowPositionals:!0}),r=t.json,o=n[0];if(!o){if(r)return h("Repository is required: pass owner/name or a repository ID from 'sazabi repos list'.");return g("Repository is required: pass owner/name or a repository ID from 'sazabi repos list'.")}let{client:i}=wS(t),a=o;if(!jH.test(o)){let{repos:s}=f(await i.repos.list(),"Couldn't list repositories (check the active project and try again)",r),l=s.filter((u)=>u.linked&&u.fullName.toLowerCase()===o.toLowerCase())[0];if(!l){let u=`Couldn't find a linked repository "${o}". Run 'sazabi repos list' to see linked repositories.`;if(r)return h(u);return g(u)}a=l.id}if(f(await i.repos.remove({id:a}),"Failed to unlink repository",r),r){j({removed:!0});return}z("Repository unlinked.")},fR=q("repos","Manage the repositories linked for code search").withSubcommands({list:v("list","List the repositories available to the project",LH).withOptions(IS).withExamples(["sazabi repos list # Available repositories with linked status","sazabi repos list --json # Include access source IDs for repos add"]).build(),add:v("add","Link repositories to the project for code search",zH).withPositionalArgs("[owner/name...]").withOptions({...IS,"access-source-id":{type:"string",description:"Access source ID from 'sazabi repos list' (repeatable); disambiguates multi-source repositories"}}).withExamples(["sazabi repos add acme/api # Link one repository by name","sazabi repos add acme/api acme/web # Link several","sazabi repos add --access-source-id <id> # Link via a specific access source"]).build(),remove:v("remove","Unlink a repository from the project",DH).withPositionalArgs("<owner/name | repo-id>").withOptions(IS).withExamples(["sazabi repos remove acme/api # Unlink a repository by name","sazabi repos remove <repo-id> # Unlink by repository ID"]).build()}).withExamples(["sazabi repos list # Available repositories","sazabi repos add acme/api # Link a repository","sazabi repos remove acme/api # Unlink a repository"]).build();H();H();te();var CS=(e)=>{process.stderr.write(`${e}
|
|
226
|
+
`)){let r=n.trim();if(r.startsWith("[")){t=/^\[\s*remote\s+"origin"\s*\]$/.test(r);continue}if(!t)continue;let o=r.match(/^url\s*=\s*(.+)$/);if(o?.[1])return o[1].trim()}return null},AV=(e)=>{let t,n,r=e.match(/^[\w.-]+@([\w.-]+):(.+)$/);if(r)t=r[1],n=r[2];else try{let s=new URL(e);t=s.hostname,n=s.pathname}catch{return null}if(!t||!n)return null;let o=n.replace(/\.git$/,"").split("/").filter((s)=>s.length>0),i=o.at(-1)??null,a=o.length>=2?o.at(-2)??null:null;return{host:t.toLowerCase(),owner:a,name:i,fullName:a&&i?`${a}/${i}`:null}},Bu=(e)=>{try{let t=$j.join(e,".git","config"),n=Dj.readFileSync(t,"utf-8"),r=xV(n);if(!r)return null;return AV(r)}catch{return null}};var Gu={githubApp:0,personal:1,integration:2},Nj=(e)=>{let t=new Map;for(let n of e){let r=t.get(n.id);if(!r){t.set(n.id,{repo:n,sourceLabels:[n.sourceLabel]});continue}if(!r.sourceLabels.includes(n.sourceLabel))r.sourceLabels.push(n.sourceLabel);let o=r.repo.linked||n.linked;if(Gu[n.source]<Gu[r.repo.source])r.repo=n;if(o!==r.repo.linked)r.repo={...r.repo,linked:o}}return[...t.values()]},TV=(e)=>{let t=e.provider==="bitbucket"?"Bitbucket":"GitHub";if(e.source==="githubApp")return`GitHub App: ${e.sourceLabel}`;if(e.source==="personal")return`Your ${t} account: ${e.sourceLabel}`;return`${t} integration: ${e.sourceLabel}`},_V=(e)=>[...e].sort((t,n)=>Gu[t.repo.source]-Gu[n.repo.source]||t.repo.sourceLabel.localeCompare(n.repo.sourceLabel)||t.repo.fullName.localeCompare(n.repo.fullName)),jV=(e)=>e===1?"repository":"repositories",RV=(e,t)=>[..._V(e).map(({repo:n,sourceLabels:r})=>({label:r.length>1?`${n.fullName} (via ${r.join(", ")})`:n.fullName,value:n.accessSourceId,hint:n.isPrivate?"private":"public",group:TV(n),preselected:t(n)})),Ql(),eu()],Uj=async(e,t)=>{let n=await e.prompts.multiselect({message:"Select the repositories to link for code search",itemNoun:"repositories",requireExplicitSelection:t.requireExplicitSelection,choices:RV(t.rows,t.preselected)});if(n.includes(oi))return"quit";if(n.includes(ni))return"back";return n.filter((r)=>typeof r==="string")},EV=async(e)=>{let t=gt(await le({label:oe({what:"Loading your repositories"}),json:e.json,work:()=>e.client.repos.list()}),"Couldn't list repositories. Try this card again");if(t===null)return await Pi(e);let n=Nj(t.repos).filter(({repo:s})=>!s.linked);if(n.length===0){if(t.repos.length>0)return N("Every available repository is already linked."),await ir(e);if(e.snapshot.state?.githubAppSkipped)return N(`No repositories are available. The GitHub App install was skipped, so none can appear. Run 'sazabi onboarding start' and choose ${Cn} to reopen the Install GitHub App step, or connect your personal GitHub account with 'sazabi connected-accounts connect github'.`),await ir(e);return N("No repositories are available yet. Check the forge connection."),await ir(e)}let r=Bu(process.cwd()),o=r?.fullName?r.fullName.toLowerCase():null,i=await Uj(e,{rows:n,preselected:(s)=>o!==null&&s.fullName.toLowerCase()===o});if(i==="back")return"back";if(i==="quit")return"hold";if(i.length===0){N("Nothing selected. No repositories linked.");return}let a=await le({label:oe({what:"Linking repositories"}),json:e.json,work:()=>e.client.repos.add({accessSourceIds:i})});if(gt(a,"Couldn't link the repositories")===null)return},LV=async(e)=>{let t=gt(await le({label:oe({what:"Loading your repositories"}),json:e.json,work:()=>e.client.repos.list()}),"Couldn't list repositories. Try this card again");if(t===null)return await Pi(e);let n=Nj(t.repos);if(n.length===0)return N("No repositories are available yet. Check the forge connection."),await ir(e);let r=await Uj(e,{rows:n,preselected:(c)=>c.linked,requireExplicitSelection:!0});if(r==="back")return"back";if(r==="quit")return"hold";let o=new Set(r);if(o.size===0){N("No repositories selected. Code search needs at least one, so the linked repositories are unchanged.");return}let i=n.filter(({repo:c})=>!c.linked&&o.has(c.accessSourceId)).map(({repo:c})=>c.accessSourceId),a=n.filter(({repo:c})=>c.linked&&!o.has(c.accessSourceId)).map(({repo:c})=>c);if(i.length===0&&a.length===0)return;let s=await le({label:oe({what:"Applying your repository selection"}),json:e.json,work:async()=>{if(i.length>0){if(!(await e.client.repos.add({accessSourceIds:i})).success)return{failure:"Couldn't link the repositories"}}for(let c of a)if(!(await e.client.repos.remove({id:c.id})).success)return{failure:`Couldn't unlink ${c.fullName}`};return{failure:null}}});if(s.failure!==null){Ue(`${s.failure}. Try this card again.`);return}},Mj={run:EV,revisit:LV,ownsBackAffordance:!0,doneNote:async(e)=>{let t=await e.client.repos.list();if(!t.success)return null;let n=new Set(t.value.repos.filter((r)=>r.linked).map((r)=>r.id)).size;return`${n} ${jV(n)}`},instructions:()=>[{command:"sazabi repos list",description:"Available repositories with linked status"},{command:"sazabi repos add --access-source-id <id>",description:"Link a repository for code search"}]};var Fj={run:async(e)=>{let t=!e.json&&ke()?an():null;try{let n=await mi({client:e.client,provider:"github",projectId:e.projectId,json:e.json,webAppUrl:e.webAppUrl,cancellation:t??void 0,reportFailure:Ue,announceCompletion:!1});if(t?.requested()){Yt("Cancelled. The GitHub App is not installed.");return}}finally{t?.dispose()}},instructions:()=>[{command:"sazabi integrations connect github",description:"Install the Sazabi GitHub App via the browser flow"}]};var Bj=async(e)=>{let t=await e.client.connectedAccounts.list();if(!t.success)return null;return t.value.accounts.some((n)=>n.provider==="github"&&!n.needsReconnect)},Gj={run:async(e)=>{let t=await le({label:oe({what:"Checking your GitHub account"}),json:e.json,work:()=>Bj(e)});if(t){mt("Your GitHub account is already connected");return}if(t===null){Ue("Couldn't list connected accounts. Try this card again.");return}let n=!e.json&&ke()?an():null;try{let r=await uv({client:e.client,provider:"github",json:e.json,cancellation:n??void 0,announceCompletion:!1});if(n?.requested()){Yt("Cancelled. Your GitHub account is not connected.");return}if(!r.ok)Ue(r.message)}finally{n?.dispose()}},doneNote:async(e)=>await Bj(e)===!1?"via teammate":null,instructions:()=>[{command:"sazabi connected-accounts connect github",description:"Connect your personal GitHub account for code search"}]};H();Qr();H();Qe();var ys=(e)=>{let t=Oe();if(!t.success)return!1;let n=dt(t.value);if(!n.success)return!1;let r=pt(t.value,{...e,...Zt(n.value)});if(!r.success)return!1;return Ne(r.value).success},bs=(e,t)=>{Fe(`${e}, but saving it to the CLI profile failed. Run '${t}' to bind it, or re-run onboarding.`)};var zV=async(e,t)=>{let n=t.map((c)=>c.organizationName),r=`${e.webAppUrl}/onboarding`;N(n.length===1?`You've been invited to ${n[0]}. Accept the invitation in the dashboard, then press Enter:`:`You've been invited to ${n.slice(0,-1).join(", ")} and ${n.at(-1)}. Accept an invitation in the dashboard, then press Enter:`),Nt(r),tt(r),await e.prompts.waitForEnter("Press Enter once you've accepted...");let o=gt(await le({label:oe({what:"Looking for the organization you joined"}),json:e.json,work:()=>e.client.organizations.list()}),"Couldn't list your organizations. Try this step again");if(o===null)return;let i=new Set(t.map((c)=>c.organizationId)),a=o.organizations.find((c)=>i.has(c.id));if(!a){Ue("The invitation hasn't been accepted yet. Accept it in the dashboard, then run 'sazabi onboarding continue'.");return}if(!ys({activeOrganizationId:a.id,organizationName:a.name,activeProjectId:void 0}))bs(`You joined ${a.name}`,`sazabi organizations use ${a.id}`)},Kj={id:"create_org",title:"Create organization",doneNote:(e)=>e.profile.organizationName??null,check:async(e)=>{if(e.organizationId)return{state:"complete",detectedFrom:"local"};return{state:"incomplete",reason:"No active organization. Create one, or accept a pending invitation."}},run:async(e)=>{go();let t=e.snapshot.state?.pendingInvitations??[];if(t.length>0)return await zV(e,t);let r=Bu(process.cwd())?.owner??void 0;for(;;){let o=await e.prompts.text({message:"Name your organization",initial:r,placeholder:r?void 0:"e.g. Acme Corp"});if(!o){N("No organization name entered.");return}let i=await le({label:oe({what:"Creating your organization"}),json:e.json,work:()=>e.client.organizations.create(o)});if(!i.success){let c=fx(i);if(c.length===0){gt(i,"Couldn't create the organization. Try again");return}let l=c.map((u)=>u.replace(/\.$/,"")).join(". ");Ue(`Couldn't create the organization. ${l}. Enter a different name.`),r=o;continue}let a=i.value;if(!ys({activeOrganizationId:a.organization.id,organizationName:a.organization.name,activeProjectId:void 0}))bs(`Organization ${a.organization.name} was created`,`sazabi organizations use ${a.organization.id}`);return}},instructions:()=>[{command:"sazabi organizations create --name <name>",description:"Create an organization"},{command:"sazabi organizations use <organization-id>",description:"Set the active organization"}]};H();wn();var vs="us-west-2",DV=new Set(Yr.options),Wj=async(e)=>{try{let t=await fetch(new URL("/api/regions",e).toString());if(!t.ok)return[];let n=await t.json();if(!Array.isArray(n))return[];return n.flatMap((r)=>{if(typeof r?.regionCode!=="string"||!DV.has(r.regionCode))return[];return[{regionCode:r.regionCode,displayLabel:typeof r.displayLabel==="string"&&r.displayLabel.length>0?r.displayLabel:r.regionCode}]})}catch{return[]}},qj=(e)=>{switch(e.split("-")[0]){case"us":case"ca":case"mx":case"sa":return"Americas";case"eu":return"Europe";case"ap":return"Asia Pacific";default:return"Other regions"}},Vj=(e)=>{let t=[...e.filter((r)=>r.regionCode===vs),...e.filter((r)=>r.regionCode!==vs)];return[...new Set(t.map((r)=>qj(r.regionCode)))].flatMap((r)=>t.filter((o)=>qj(o.regionCode)===r).map((o)=>({label:o.displayLabel,value:o.regionCode,hint:o.regionCode,preselected:o.regionCode===vs,group:r})))};var $V=async(e)=>{let t=await le({label:oe({what:"Loading regions"}),json:e.json,work:()=>Wj(e.platformApiBaseUrl)});if(t.length===0){N(`Couldn't load the region list. Using the default region (${vs}).`);return}return e.prompts.select({message:"Choose the region for your Sazabi backend",choices:Vj(t)})},Hj=(e,t,n)=>{let r=ys({activeOrganizationId:e,activeProjectId:t});if(!r)bs(n,`sazabi projects use ${t}`);return r},Zj={id:"create_project",title:"Create project",doneNote:async(e)=>{if(!e.projectId)return null;let t=await e.client.projects.get(e.projectId);if(!t.success)return null;let{name:n,region:r}=t.value.project;return`${n}, ${r}`},check:async(e)=>{if(e.organizationId&&e.projectId)return{state:"complete",detectedFrom:"local"};if(!e.organizationId)return{state:"incomplete",reason:"No active organization. Complete the organization step first."};return{state:"incomplete",reason:e.snapshot.state?.projectId?"No active project. The organization's project isn't bound to this CLI profile yet.":"No active project. Choose a region to create one."}},run:async(e)=>{let t=e.organizationId;if(!t){N("No active organization. Run 'sazabi onboarding continue' to set one up first.");return}let n=e.snapshot.state?.projectId;if(n){Hj(t,n,"The organization's project was found");return}go(),ce("Configure your project");let r=await $V(e),o=gt(await le({label:oe({what:"Setting up your project"}),json:e.json,work:()=>e.client.onboarding.ensureDefaultProject({organizationId:t,...r?{region:r}:{}})}),"Couldn't set up the project. Try this step again");if(o===null)return;if(!o.created)N("Your organization already has a project, so no new one was created.");return Hj(t,o.project.id,o.created?`Project ${o.project.name} was created`:"The organization's project was found"),o.created?"created":void 0},instructions:()=>[{command:"sazabi onboarding continue",description:"Create the project (choose a region), or bind the organization's existing project"},{command:"sazabi projects create --name <name>",description:"Create a project with a name of your own instead"},{command:"sazabi projects use <project-id>",description:"Set the active project"}]};var NV=["slack","teams"],UV=async(e)=>{let t=await e.client.integrations.listConnections();if(!t.success)return!1;return t.value.connections.some((n)=>NV.includes(n.provider)&&n.isActive)},Jj={run:async(e)=>{if(await le({label:oe({what:"Checking your chat connection"}),json:e.json,work:()=>UV(e)})){mt("A chat app is already connected");return}let n=!e.json&&ke()?an():null;try{if(await mi({client:e.client,provider:"slack",projectId:e.projectId,json:e.json,webAppUrl:e.webAppUrl,cancellation:n??void 0,reportFailure:Ue,announceCompletion:!1}),n?.requested()){Yt("Cancelled. Slack is not connected.");return}}finally{n?.dispose()}},instructions:()=>[{command:"sazabi integrations connect slack",description:"Connect Slack via the browser flow"}]};var Ku={id:"sign_in",title:"Sign in",listed:!1,check:async(e)=>{let t=await le({label:oe({what:"Checking your session"}),json:e.json,work:()=>e.client.me()});if(!t.success)return{state:"incomplete",reason:!e.hasCredentials||t.statusCode===401?"Not signed in. Run 'sazabi auth sign-in' to authenticate.":`Couldn't check your session (${t.error}). Try again in a moment.`};if(t.value.credentialType!=="user")return{state:"incomplete",reason:"Signed in with a secret key. Onboarding needs a personal user token (billing and finishing onboarding are user-only). Run 'sazabi auth sign-in'."};return{state:"complete",detectedFrom:"server"}},run:async(e)=>{go();for(let t=0;;t+=1){if(t>0){if(await e.prompts.select({message:"Create a Sazabi account",choices:[{label:"Try again",value:"signup",hint:"Opens the sign-up page in your browser"},rr]})==="quit")return"quit"}let n=!e.json&&ke()?an():null,r=n?{cancellation:n}:{},o=null;try{o=await Wo({json:e.json,apiBaseUrl:e.apiBaseUrl,authBaseUrl:e.platformApiBaseUrl,reportFailure:Ue,...r})}finally{n?.dispose()}if(n?.requested()){Yt(tu);continue}if(o===null)continue;return}},instructions:()=>[{command:"sazabi auth sign-in",description:"Sign in with a personal user token via the browser"}]};H();H();var Yj=60,MV={topLeft:"┌",topRight:"┐",bottomLeft:"└",bottomRight:"┘",leftTee:"├",rightTee:"┤",horizontal:"─",vertical:"│",marker:"●"},FV={topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",leftTee:"+",rightTee:"+",horizontal:"-",vertical:"|",marker:"*"},BV=" · ",GV=", ",KV=(e=process.env)=>{let t=e.LC_ALL??e.LC_CTYPE??e.LANG??"";if(t==="")return!0;return/utf-?8/i.test(t)},qV=(e)=>{switch(e){case"critical":case"high":return _.error(e);case"medium":return _.warning(e);case"low":return _.info(e);default:return e}},Xj=(e,t)=>{let n=[],r="";for(let o of e.split(/\s+/).filter((i)=>i!=="")){if(r==="")r=o;else if(r.length+1+o.length<=t)r=`${r} ${o}`;else n.push(r),r=o;while(r.length>t)n.push(r.slice(0,t)),r=r.slice(t)}if(r!=="")n.push(r);return n.length>0?n:[""]},Qj=(e,t,n)=>`${e}${" ".repeat(Math.max(0,n-t))}`,WV=(e)=>{let t=e.ascii??!KV(),n=t?FV:MV,r=t?GV:BV,o=Math.min(Yj,process.stdout.columns||Yj),i=Math.max(32,e.width??o),s=e.status==="resolved"?_.success:_.error,c=ms[e.status],l=i-4,u=(Z,re)=>s(Z+n.horizontal.repeat(i-2)+re),d=(Z,re)=>`${s(n.vertical)} ${Qj(Z,re,l)} ${s(n.vertical)}`,p=[u(n.topLeft,n.topRight)],m=`${n.marker} ${jt.name}`,b=`${s(n.marker)} ${_.bold(jt.name)}`,y=[jt.component,jt.severity,c].join(r),I=[_.muted(jt.component),qV(jt.severity),s(c)].join(_.muted(r));if(m.length+2+y.length<=l){let Z=l-m.length-y.length;p.push(d(`${b}${" ".repeat(Z)}${I}`,m.length+Z+y.length))}else{p.push(d(b,m.length));for(let Z of Xj(y,l-2))p.push(d(_.muted(` ${Z}`),Z.length+2))}p.push(u(n.leftTee,n.rightTee));let C=l-4,B=(Z,re)=>d(_.muted(Z+n.horizontal.repeat(l-2)+re),l),V=(Z,re)=>d(`${_.muted(n.vertical)} ${Qj(Z,re,C)} ${_.muted(n.vertical)}`,C+4);p.push(B(n.topLeft,n.topRight)),p.push(V(_.muted(Lu.toUpperCase()),Lu.length));for(let Z of Xj(jt.description,C))p.push(V(Z,Z.length));p.push(B(n.bottomLeft,n.bottomRight));let ee=oS();return p.push(d(_.muted(ee),ee.length)),p.push(u(n.bottomLeft,n.bottomRight)),p},qu=(e)=>{for(let t of WV({status:e}))console.log(t)};var eR=(e)=>({name:jt.name,component:jt.component,severity:jt.severity,status:ms[e].toLowerCase(),description:jt.description,occurredAt:nS().toISOString()}),tR=()=>{ce(rS),N(eS)},nR=async(e)=>gt(await le({label:oe({what:"Resolving the issue"}),json:e.json,work:()=>e.client.onboarding.completeSampleIssue(e.projectId?{projectId:e.projectId}:void 0)}),"Couldn't resolve the test issue. Try this card again")!==null,oR={run:async(e)=>{if(e.json){j(eR("open")),await nR(e);return}if(tR(),qu("open"),ke()){if(await e.prompts.select({message:"Resolve this issue to continue",choices:[{label:"Resolve",value:"resolve",preselected:!0},{label:mo,value:"quit"}]})==="quit")return"hold"}if(!await nR(e))return"hold";if(qu("resolved"),ke()){if(await e.prompts.select({message:"Continue",choices:[{label:"Continue",value:"continue",preselected:!0},{label:mo,value:"quit"}]})==="quit")return"hold"}},ownsBackAffordance:!0,renderRevisit:async(e)=>{if(e.json){j(eR("resolved"));return}tR(),qu("resolved")},instructions:()=>[{command:"sazabi onboarding continue",description:"Resolve the test issue to complete this step"}]};var fS=[Ku,Kj],Ss=Zj,VV={set_up_billing:Cj,connect_github_account:Gj,install_github_app:Fj,configure_code_search:Mj,install_slack_app:Jj,configure_slack_alerts:zj,trigger_sample_issue:oR},Oi=(e)=>VV[e],Wu={run:async(e,t)=>{let n=Oi(e.id);if(!n){N(`This step isn't available in this CLI version. Finish it in the dashboard: ${t.webAppUrl}/onboarding`);return}return await n.run(t)},instructions:(e,t)=>{let n=Oi(e.id);if(n)return n.instructions(t);return[{url:`${t.webAppUrl}/onboarding`,description:e.instructions}]},doneNote:async(e,t)=>await Oi(e.id)?.doneNote?.(t)??null,renderRevisit:async(e,t)=>{await Oi(e.id)?.renderRevisit?.(t)},ownsBackAffordance:(e)=>Oi(e.id)?.ownsBackAffordance??!1,revisit:(e)=>Oi(e.id)?.revisit??null};var bS={...O,"project-id":{type:"string"},"organization-id":{type:"string"}},Vu={...x,"project-id":{type:"string",description:"Override active project ID"},"organization-id":{type:"string",description:"Override active organization ID"}},vS=(e)=>({token:e.token,projectId:e["project-id"],organizationId:e["organization-id"],apiBaseUrl:e["api-base-url"],json:Boolean(e.json)}),rR=async(e,t)=>{let n=await le({label:oe({what:"Loading your setup"}),json:Boolean(e.json),work:()=>Uu(e)});if(t==="continue"&&!e.json&&ke()){let o=await Zn(n,Ku);if(o.state==="incomplete")return g(n.hasCredentials?o.reason:`${o.reason} To create a new account instead, run 'sazabi start'.`)}{let o=await le({label:oe({what:"Checking your project"}),json:Boolean(e.json),work:()=>lS(n)});if(!o.success){if(e.json)return h(o.error);return g(o.error)}}let r=await wj({preamble:fS,projectGate:Ss,interpreter:Wu,json:Boolean(e.json),buildContext:()=>Uu(e),initialContext:n});if(r!==0)process.exit(r)},HV=async(e)=>{if(e.json||!ke())return!0;if(e.token?.trim()||process.env.SAZABI_TOKEN?.trim())return!0;if(!f(vt(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",!1).token?.trim())return!0;if(await qo({message:"You're already signed in. Sign out and create a new account?",choices:[{label:"Sign out",value:"sign-out"},{label:"No",value:"stay"}]})==="stay")return N("Run 'sazabi onboarding continue' to keep setting up your current account."),!1;return Vb({json:!1}),!0},ZV=async(e)=>{let{values:t}=S(e,bS),n=vS(t);if(!await HV(n))return;await rR(n,"start")},JV=async(e)=>{let{values:t}=S(e,bS);await rR(vS(t),"continue")},YV=(e)=>{switch(e.state){case"done":return"complete";case"pending":return"incomplete";case"skipped":return"skipped";case"not-applicable":return"not applicable";case"unavailable":return"unavailable"}},XV=(e,t)=>({id:e.card.id,label:e.card.label,skippable:Hn(e.card.id),status:YV(e.status),...e.status.state==="unavailable"?{skippedDependency:e.status.dependency}:{},actions:Wu.instructions(e.card,t)}),Is=[...fS.map((e)=>({step:e,position:"pre-flow"})),{step:Ss,position:"gate-line"},{step:dS,position:"post-flow"}],QV=(e,t,n)=>({id:e.id,label:e.title,status:t.state,...t.state==="incomplete"?{reason:t.reason}:{},actions:e.instructions(n)}),eH=async(e)=>{let{values:t}=S(e,bS),n=vS(t),r=Boolean(n.json),o=await le({label:oe({what:"Loading your setup"}),json:r,work:()=>Uu(n)});{let y=await le({label:oe({what:"Checking your project"}),json:r,work:()=>lS(o)});if(!y.success){if(r)return h(y.error);return g(y.error)}}let i=Ij(o);if(i.kind==="read-error"){let y=`Couldn't load the onboarding state (${i.error}). Try again in a moment.`;if(r)return h(y);return g(y)}let a=i.rows,s="Project-scoped steps are hidden until a project is set. Run 'sazabi onboarding continue' to set one up.",c=new Map,l=(y)=>c.get(y.id)??{state:"incomplete",reason:"Status unavailable."},u=new Map,d=new Map;if(await Promise.all(Is.map(async({step:y})=>{c.set(y.id,await Zn(o,y))})),!r){let y=[...Is.map(({step:I})=>I),Ss].filter((I)=>l(I).state==="complete");await le({label:oe({what:"Loading your setup"}),json:r,work:()=>Promise.all([...y.map((I)=>ki(I,o).then((C)=>u.set(I.id,C)).catch(()=>u.set(I.id,null))),...a.filter((I)=>I.status.state==="done").map((I)=>Promise.resolve(Wu.doneNote?.(I.card,o)).then((C)=>d.set(I.card.id,C??null)).catch(()=>d.set(I.card.id,null)))])})}if(r){j({gates:Is.map(({step:y})=>QV(y,l(y),o)),onboarding:a.map((y)=>XV(y,o)),...i.kind==="org-only"?{note:s}:{}});return}if(!o.hasCredentials)N("Not signed in. Completion state is unavailable. Run 'sazabi auth sign-in' first.");let p=new Map(a.map((y)=>[y.card.id,y])),m=(y)=>{let I=l(y),C=Ii({step:y,status:I,detail:u.get(y.id)??null});if(C!==null)console.log(C)},b=(y)=>{let I=y.status.state==="done"?d.get(y.card.id)??null:null,C=or({card:y.card,status:y.status,detail:I});if(C!==null)console.log(C)};ce("Onboarding");for(let{step:y,position:I}of Is)if(I==="pre-flow")m(y);for(let y of Bt){if(y.kind==="gate"){m(Ss);continue}let I=p.get(y.id);if(I)b(I)}for(let{step:y,position:I}of Is)if(I==="post-flow")m(y);if(i.kind==="org-only")console.log(""),N(s)},SS=q("onboarding","Guided setup for a project from the terminal").withOptions(Vu).withSubcommands({start:v("start","Start onboarding a new account (offers to sign out first when signed in)",ZV).withOptions(Vu).withExamples(["sazabi onboarding start # Walk every step, showing completed ones","sazabi onboarding start --json # Emit the next actionable step as JSON"]).build(),continue:v("continue","Run the onboarding flow from the first incomplete step",JV).withOptions(Vu).withExamples(["sazabi onboarding continue # Resume at the first incomplete step","sazabi onboarding continue --json # Emit the next actionable step as JSON"]).build(),progress:v("progress","Read-only onboarding checklist",eH).withOptions(Vu).withExamples(["sazabi onboarding progress # Every step with its status","sazabi onboarding progress --json # Full checklist as JSON, with each step's actions"]).build()}).withExamples(["sazabi onboarding continue # Resume at the first incomplete step","sazabi onboarding start # Walk every step from the top","sazabi onboarding progress # Read-only checklist"]).build(),yS=SS.subcommands?.start;if(!yS)throw Error('onboarding subcommand "start" is missing');var iR={...yS,name:"start",examples:[...(yS.examples??[]).map((e)=>e.replace("sazabi onboarding start","sazabi start")),"sazabi onboarding start # Canonical form; sazabi start is its permanent alias"]};H();se();te();Qe();var aR={id:{label:"ID",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},slug:{label:"Slug",type:{kind:"string"}},role:{label:"Role",type:{kind:"nullable-string"}}},tH={schema:aR,columns:["id","name","slug","role"],header:"Organizations",emptyMessage:"No organizations found."},sR={layout:"field-list",schema:aR,fields:["id","name","slug","role"]},nH=async(e)=>{let t=A({tokenFlag:e.token,jsonMode:e.json}),n=T({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:e.json}),r=f(await n.organizations.list(),"Couldn't list organizations (check your token and try again)",e.json);D(tH,r.organizations,{json:e.json})},oH=async(e,t)=>{let n=A({tokenFlag:t.token,jsonMode:t.json}),r=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t.json),o=T({token:n.token,organizationId:e,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),i=f(await o.organizations.get(e),"Couldn't fetch organization (run 'sazabi organizations list' to see organization IDs)",t.json).organization,a=f(await o.projects.list({organizationId:e}),"Couldn't fetch organization projects (check the organization ID and try again)",t.json).projects,s=f(dt(r),"Couldn't resolve profile (run 'sazabi profiles list' to see available profiles)",t.json),c=s.activeProjectId&&a.some((p)=>p.id===s.activeProjectId)?s.activeProjectId:a[0]?.id,l=i.id!==s.activeOrganizationId,u=c!==s.activeProjectId,d=f(pt(r,{activeOrganizationId:i.id,organizationName:i.name,activeProjectId:c,...(l||u)&&Zt(s)}),"Failed to update profile",t.json);if(f(Ne(d),"Failed to persist active organization",t.json),t.json){j({organization:i,activeProjectId:f(dt(d),"Couldn't resolve profile (run 'sazabi profiles list' to see available profiles)",t.json).activeProjectId});return}z(`Active organization set to ${i.name}.`)},rH=async(e,t)=>{let n=A({tokenFlag:t.token,jsonMode:t.json}),r=T({token:n.token,organizationId:n.organizationId,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),{organization:o}=f(await r.organizations.create(e),"Failed to create organization",t.json);if(iH(o.id,o.name),t.json){j({organization:o});return}z(`Organization ${o.name} created.`),R(sR,{...o,role:"admin"},{json:t.json})},iH=(e,t)=>{let n=Oe();if(!n.success)return;let r=n.value,o=dt(r);if(!o.success)return;let i=pt(r,{activeOrganizationId:e,organizationName:t,activeProjectId:void 0,...Zt(o.value)});if(i.success)Ne(i.value)},aH=async(e,t)=>{let n=A({tokenFlag:t.token,organizationIdFlag:t.organizationId,jsonMode:t.json}),r=T({token:n.token,organizationId:n.organizationId,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),o=f(await r.organizations.rename(e,n.organizationId),"Failed to rename organization",t.json);sH(o.organization.id,o.organization.name),R(sR,o.organization,{json:t.json})},sH=(e,t)=>{let n=Oe();if(!n.success)return;let r=n.value,o=dt(r);if(!o.success)return;if(o.value.activeOrganizationId!==e)return;let i=pt(r,{organizationName:t});if(i.success)Ne(i.value)},cR=q("organizations","Manage organizations").withSubcommands({list:v("list","List organizations available to the current credential",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0});if(n.length>0){let r=n.join(", ");if(t.json)return h(`Unexpected arguments: ${r}. Run 'sazabi organizations -h' for usage.`);return g(`Unexpected arguments: ${r}. Run 'sazabi organizations -h' for usage.`)}await nH({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi organizations list # List available organizations"]).build(),create:v("create","Create an organization and make it the active one",async(e)=>{let{values:t}=S(e,{token:{type:"string"},name:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}}),n=t.name?.trim();if(!n){if(t.json)return h("--name is required.");return g("--name is required.")}await rH(n,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},name:{type:"string",description:"Organization display name (required)"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(['sazabi organizations create --name "Acme Corp" # Create an organization']).build(),use:v("use","Set the active organization for future commands",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Organization ID is required.");return g("Organization ID is required.")}await oH(r,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi organizations use org_123 # Set the active organization"]).build(),rename:v("rename","Rename the active organization",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},"organization-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Organization name is required.");return g("Organization name is required.")}if(n.length>1){let o=n.slice(1).join(", ");if(t.json)return h(`Unexpected arguments: ${o}. Run 'sazabi organizations -h' for usage.`);return g(`Unexpected arguments: ${o}. Run 'sazabi organizations -h' for usage.`)}await aH(r,{token:t.token,organizationId:t["organization-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(['sazabi organizations rename "Observed Platform" # Rename the active organization']).build()}).withExamples(["sazabi organizations list # List available organizations","sazabi organizations use org_123 # Set the active organization",'sazabi organizations rename "Observed Platform" # Rename the active organization']).build();H();te();Qe();var cH={name:{label:"Profile",type:{kind:"string"}},active:{label:"Active",type:{kind:"custom",render:(e)=>e?_.success("*"):"",serialize:(e)=>Boolean(e)}}},lH=(e)=>{let t=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",e.json),n=Object.keys(t.profiles).map((r)=>({name:r,active:r===t.activeProfile}));D({schema:cH,columns:["name","active"],header:"Profiles",emptyMessage:"No profiles configured."},n,{json:e.json})},uH=(e,t)=>{let n=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t.json);if(!n.profiles[e]){let r=`Profile '${e}' does not exist. Run 'sazabi profiles list' to see available profiles.`;if(t.json)h(r);g(r)}if(n.activeProfile=e,f(Ne(n),"Failed to write settings",t.json),t.json){j({activeProfile:e});return}z(`Active profile set to '${e}'.`)},dH=(e,t)=>{let n=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t.json);if(n.profiles[e]){let r=`Profile '${e}' already exists.`;if(t.json)h(r);g(r)}if(n.profiles[e]={},f(Ne(n),"Failed to write settings",t.json),t.json){j({created:e});return}z(`Profile '${e}' created.`)},pH=(e,t)=>{let n=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t.json);if(!n.profiles[e]){let r=`Profile '${e}' does not exist. Run 'sazabi profiles list' to see available profiles.`;if(t.json)h(r);g(r)}if(e===n.activeProfile){let r=`Cannot delete the active profile '${e}'. Switch to a different profile first with 'sazabi profiles use <name>'.`;if(t.json)h(r);g(r)}if(delete n.profiles[e],f(Ne(n),"Failed to write settings",t.json),t.json){j({deleted:e});return}z(`Profile '${e}' deleted.`)},lR=q("profiles","Manage named CLI profiles").withSubcommands({list:v("list","List all profiles",async(e)=>{let{values:t}=S(e,{json:{type:"boolean"}});lH({json:t.json})}).withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(["sazabi profiles list # List all profiles"]).build(),use:v("use","Set the active profile",async(e)=>{let{values:t,positionals:n}=S(e,{json:{type:"boolean"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Profile name is required. Usage: sazabi profiles use <name>");return g("Profile name is required. Usage: sazabi profiles use <name>")}uH(r,{json:t.json})}).withPositionalArgs("<name>").withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(["sazabi profiles use staging # Switch to staging profile"]).build(),create:v("create","Create a new empty profile",async(e)=>{let{values:t,positionals:n}=S(e,{json:{type:"boolean"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Profile name is required. Usage: sazabi profiles create <name>");return g("Profile name is required. Usage: sazabi profiles create <name>")}dH(r,{json:t.json})}).withPositionalArgs("<name>").withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(["sazabi profiles create staging # Create a new profile"]).build(),delete:v("delete","Delete a profile",async(e)=>{let{values:t,positionals:n}=S(e,{json:{type:"boolean"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Profile name is required. Usage: sazabi profiles delete <name>");return g("Profile name is required. Usage: sazabi profiles delete <name>")}pH(r,{json:t.json})}).withPositionalArgs("<name>").withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(["sazabi profiles delete staging # Delete a profile"]).build()}).withExamples(["sazabi profiles list # List all profiles","sazabi profiles use staging # Switch to staging profile","sazabi profiles create local # Create a new profile","sazabi profiles delete staging # Delete a profile"]).build();H();se();te();Qe();var mH={id:{label:"ID",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},region:{label:"Region",type:{kind:"string"}},active:{label:"Active",type:{kind:"custom",render:(e)=>e?_.success("*"):"",serialize:(e)=>e}},url:{label:"URL",type:{kind:"string"}}},gH={schema:mH,columns:["id","name","region","active","url"],header:"Projects",emptyMessage:"No projects found."},hH={id:{label:"ID",type:{kind:"string"}},name:{label:"Name",type:{kind:"string"}},region:{label:"Region",type:{kind:"string"}},organizationId:{label:"Organization",type:{kind:"string"}}},fH={layout:"field-list",schema:hH,fields:["id","name","region","organizationId"],title:"Project"},yH=async(e)=>{let t=A({tokenFlag:e.token,organizationIdFlag:e.organizationId,jsonMode:e.json}),n=T({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:e.json}),r=f(await n.projects.create({name:e.name,...e.organizationId?{organizationId:e.organizationId}:{},...e.region?{region:e.region}:{}}),"Failed to create project",e.json);if(R(fH,{id:r.project.id,name:r.project.name,region:r.project.region,organizationId:r.project.organizationId},{json:e.json,contract:r.project}),!e.json)z(`Project ${r.project.name} created.`)},bH=async(e)=>{let t=A({tokenFlag:e.token,organizationIdFlag:e.organizationId,jsonMode:e.json}),n=T({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:e.json}),o=f(await n.projects.list({organizationId:t.organizationId}),"Couldn't list projects (check the active organization and try again)",e.json).projects.map((i)=>({...i,active:i.id===t.projectId,url:uo(i.id)}));D(gH,o,{json:e.json})},vH=async(e,t)=>{let n=A({tokenFlag:t.token,jsonMode:t.json}),r=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t.json),o=T({token:n.token,organizationId:n.organizationId,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),i=f(await o.projects.get(e),"Couldn't fetch project (run 'sazabi projects list' to see project IDs)",t.json).project,a=Ht(r),s=r.profiles[a],c=i.organizationId!==s?.activeOrganizationId,l=i.id!==s?.activeProjectId,u=f(pt(r,{activeOrganizationId:i.organizationId,activeProjectId:i.id,...c&&{organizationName:void 0},...(c||l)&&Zt(s)}),"Failed to update profile",t.json);if(f(Ne(u),"Failed to persist active project",t.json),t.json){j({project:i});return}z(`Active project set to ${i.name}.`)},uR=q("projects","Manage projects").withSubcommands({list:v("list","List projects in the active organization",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},"organization-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0});if(n.length>0){let r=n.join(", ");if(t.json)return h(`Unexpected arguments: ${r}. Run 'sazabi projects -h' for usage.`);return g(`Unexpected arguments: ${r}. Run 'sazabi projects -h' for usage.`)}await bH({token:t.token,organizationId:t["organization-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi projects list # List projects in the active organization"]).build(),use:v("use","Set the active project for future commands",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Project ID is required.");return g("Project ID is required.")}await vH(r,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi projects use 11111111-1111-4111-8111-111111111111 # Set the active project"]).build(),create:v("create","Create a new project in the active organization",async(e)=>{let{values:t,positionals:n}=S(e,{...O,name:{type:"string"},region:{type:"string"},"organization-id":{type:"string"}},{allowPositionals:!0});if(n.length>0){let r=n.join(", ");if(t.json)return h(`Unexpected arguments: ${r}. Run 'sazabi projects -h' for usage.`);return g(`Unexpected arguments: ${r}. Run 'sazabi projects -h' for usage.`)}if(!t.name){if(t.json)return h("--name is required.");return g("--name is required.")}await yH({name:t.name,region:t.region,organizationId:t["organization-id"],token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({...x,name:{type:"string",required:!0,description:"Project name (required)"},region:{type:"string",description:"AWS region for the project (defaults to us-west-2)"},"organization-id":{type:"string",description:"Override organization selection"}}).withExamples(['sazabi projects create --name "My Project" # Create a project in the active organization','sazabi projects create --name "EU App" --region eu-central-1 # Create in a specific region']).build()}).withExamples(["sazabi projects list # List projects in the active organization","sazabi projects use 11111111-1111-4111-8111-111111111111 # Set the active project",'sazabi projects create --name "My Project" # Create a project']).build();H();se();te();var SH={id:{label:"ID",type:{kind:"string"}},projectId:{label:"Project",type:{kind:"string"}},repositoryFullName:{label:"Repository",type:{kind:"string"}},githubPullRequestId:{label:"PR #",type:{kind:"number"}},title:{label:"Title",type:{kind:"nullable-string"}},url:{label:"URL",type:{kind:"nullable-string"}},status:{label:"Status",type:{kind:"nullable-string"}},reviewState:{label:"Review",type:{kind:"nullable-string"}},checksState:{label:"Checks",type:{kind:"nullable-string"}},requestedByUserId:{label:"Requested by",type:{kind:"nullable-string"}},githubAuthorLogin:{label:"GitHub author",type:{kind:"nullable-string"}},threadId:{label:"Thread",type:{kind:"nullable-string"}},runId:{label:"Run",type:{kind:"nullable-string"}},createdAt:{label:"Created",type:{kind:"date"}},mergedAt:{label:"Merged",type:{kind:"nullable-date"}},closedAt:{label:"Closed",type:{kind:"nullable-date"}}},IH=["id","projectId","repositoryFullName","githubPullRequestId","title","url","status","reviewState","checksState","requestedByUserId","githubAuthorLogin","threadId","runId","createdAt","mergedAt","closedAt"],kH={schema:SH,columns:["repositoryFullName","githubPullRequestId","title","status","createdAt"],jsonFields:IH,header:"Pull requests",emptyMessage:"No pull requests found."},wH=async(e)=>{let t=A({tokenFlag:e.token,jsonMode:e.json}),n=T({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:e.json}),r=f(await n.pullRequests.list({status:e.status,repositoryFullName:e.repository,requestedByUserId:e.requestedBy,limit:e.limit,cursor:e.cursor}),"Couldn't list pull requests (check the active project and try again)",e.json);D(kH,r.pullRequests,{json:e.json,nextCursor:r.nextCursor})},dR=q("pull-requests","List pull requests opened by Sazabi").withSubcommands({list:v("list","List pull requests Sazabi opened in the active project",async(e)=>{let{values:t}=S(e,{...O,status:{type:"string"},repository:{type:"string"},"requested-by":{type:"string"},mine:{type:"boolean"},limit:{type:"string"},cursor:{type:"string"}}),n=["open","merged","closed"];if(t.status&&!n.includes(t.status)){let i=`Invalid --status "${t.status}". Must be one of: ${n.join(", ")}.`;if(t.json)return h(i);return g(i)}let r=t.limit?Number(t.limit):void 0;if(r!==void 0&&(Number.isNaN(r)||r<1||r>100)){if(t.json)return h("Invalid --limit. Must be an integer between 1 and 100.");return g("Invalid --limit. Must be an integer between 1 and 100.")}let o=t.mine?"me":t["requested-by"];await wH({token:t.token,json:t.json,apiBaseUrl:t["api-base-url"],status:t.status,repository:t.repository,requestedBy:o,limit:r,cursor:t.cursor})}).withOptions({...x,status:{type:"string",description:"Filter by status: open, merged, or closed"},repository:{type:"string",description:"Filter by repository full name, for example owner/repo"},"requested-by":{type:"string",description:"Filter by the Sazabi user ID that requested the PR (or 'me')"},mine:{type:"boolean",description:"Only show pull requests you requested (requires user authentication)"},limit:{type:"string",description:"Maximum number of pull requests to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from a previous response"}}).withExamples(["sazabi pull-requests list # List PRs Sazabi opened in the active project","sazabi pull-requests list --status open --mine # Your open PRs","sazabi pull-requests list --repository sazabi/monorepo --json # PRs in one repo as JSON"]).build()}).withExamples(["sazabi pull-requests list # List PRs Sazabi opened","sazabi pull-requests list --status open --mine # Your open PRs","sazabi pull-requests list --repository owner/repo # PRs in one repo"]).build();H();se();te();var CH={priority:{label:"#",type:{kind:"number"}},kind:{label:"Kind",type:{kind:"string"}},targetId:{label:"Target",type:{kind:"string"}},status:{label:"Status",type:{kind:"custom",render:(e)=>e==="connected"?_.success("connected"):_.info("recommended"),serialize:(e)=>e}},roiScore:{label:"ROI",type:{kind:"number"}},components:{label:"Because you run",type:{kind:"custom",render:(e)=>{let t=e.map((n)=>n.name);return t.length>0?t.join(", "):_.muted("—")},serialize:(e)=>e}}},PH={schema:CH,columns:["priority","kind","targetId","status","roiScore","components"],header:"Recommendations",emptyMessage:"No recommendations found."},pR=["log_source","mcp_connector","sandbox_cli","integration"],mR=["connected","recommended"],OH=async(e)=>{if(e.kind&&!pR.includes(e.kind)){let i=`Invalid --kind: ${e.kind}. Expected one of: ${pR.join(", ")}.`;if(e.json)return h(i);return g(i)}if(e.status&&!mR.includes(e.status)){let i=`Invalid --status: ${e.status}. Expected one of: ${mR.join(", ")}.`;if(e.json)return h(i);return g(i)}let t=A({tokenFlag:e.token,projectIdFlag:e.projectId,organizationIdFlag:e.organizationId,jsonMode:e.json}),n=T({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:e.json}),o=f(await n.recommendations.list(),"Couldn't list recommendations (check the active project and try again)",e.json).recommendations.filter((i)=>(!e.kind||i.kind===e.kind)&&(!e.status||i.status===e.status));D(PH,o,{json:e.json})},xH={...O,"project-id":{type:"string"},"organization-id":{type:"string"},kind:{type:"string"},status:{type:"string"}},AH={...x,"project-id":{type:"string",description:"Override active project ID"},"organization-id":{type:"string",description:"Override active organization ID"},kind:{type:"string",description:"Filter by kind (log_source, mcp_connector, sandbox_cli, integration)"},status:{type:"string",description:"Filter by status (connected, recommended)"}},gR=q("recommendations","View setup recommendations for a project").withSubcommands({list:v("list","List setup recommendations for the active project",async(e)=>{let{values:t}=S(e,xH);await OH({token:t.token,projectId:t["project-id"],organizationId:t["organization-id"],apiBaseUrl:t["api-base-url"],json:t.json,kind:t.kind,status:t.status})}).withOptions(AH).withExamples(["sazabi recommendations list # List all recommendations","sazabi recommendations list --status recommended # Only not-yet-connected items","sazabi recommendations list --kind log_source # Only log sources","sazabi recommendations list --json # Output as JSON"]).build()}).withExamples(["sazabi recommendations list # List all recommendations","sazabi recommendations list --json # Output as JSON"]).build();H();se();te();var TH={id:{label:"ID",type:{kind:"id"}},accessSourceId:{label:"Access source",type:{kind:"string"}},fullName:{label:"Repository",type:{kind:"string"}},sourceLabel:{label:"Source",type:{kind:"string"}},source:{label:"Source kind",type:{kind:"string"}},provider:{label:"Provider",type:{kind:"string"}},linked:{label:"Linked",type:{kind:"boolean"}},defaultBranch:{label:"Default branch",type:{kind:"nullable-string"}},isPrivate:{label:"Private",type:{kind:"boolean"}}},hR={schema:TH,columns:["id","fullName","sourceLabel","provider","linked"],jsonFields:["id","accessSourceId","fullName","source","sourceLabel","provider","linked","defaultBranch","isPrivate"],header:"Repositories",emptyMessage:"No repositories available. Connect a forge with 'sazabi integrations connect github' first."},_H={...hR,header:"Linked repositories"},kS={...O,"project-id":{type:"string"}},IS={...x,"project-id":{type:"string",description:"Override active project ID"}},wS=(e)=>{let t=e.json,n=A({tokenFlag:e.token,projectIdFlag:e["project-id"],jsonMode:t});return{client:T({token:n.token,organizationId:n.organizationId,projectId:n.projectId,apiBaseUrlFlag:e["api-base-url"],jsonMode:t}),json:t}},jH=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,RH=async(e)=>{let{name:t,repos:n,json:r}=e,o=n.filter((s)=>s.fullName.toLowerCase()===t.toLowerCase());if(o.length===0){let s=n.filter((u)=>u.fullName.toLowerCase().includes(t.toLowerCase())).slice(0,5).map((u)=>u.fullName),c=s.length>0?` Did you mean: ${s.join(", ")}?`:"",l=`Couldn't find repository "${t}". Run 'sazabi repos list' to see available repositories.${c}`;if(r)return h(l);return g(l)}if(o.length===1){let s=o[0];if(!s)return g("Unreachable");return s.accessSourceId}if(!r&&ke())return qo({message:`"${o[0]?.fullName}" is available through several sources. Link via which?`,choices:o.map((s)=>({label:`${s.fullName} (${s.sourceLabel})`,value:s.accessSourceId}))});let i=o.map((s)=>`${s.accessSourceId} (${s.sourceLabel})`).join(", "),a=`"${t}" is available through several sources. Pass --access-source-id with one of: ${i}.`;if(r)return h(a);return g(a)},EH=(e)=>{if(Array.isArray(e))return e.filter((t)=>typeof t==="string");return typeof e==="string"?[e]:[]},LH=async(e)=>{let{values:t}=S(e,kS),{client:n,json:r}=wS(t),{repos:o}=f(await n.repos.list(),"Couldn't list repositories (check the active project and try again)",r);D(hR,o,{json:r})},zH=async(e)=>{let{values:t,positionals:n}=S(e,{...kS,"access-source-id":{type:"string",multiple:!0}},{allowPositionals:!0}),r=t.json,o=EH(t["access-source-id"]);if(o.length===0&&n.length===0){if(r)return h("Provide repositories to link: pass owner/name (from 'sazabi repos list') or --access-source-id.");return g("Provide repositories to link: pass owner/name (from 'sazabi repos list') or --access-source-id.")}let{client:i}=wS(t);if(n.length>0){let{repos:s}=f(await i.repos.list(),"Couldn't list repositories (check the active project and try again)",r);for(let c of n)o.push(await RH({name:c,repos:s,json:r}))}let{repos:a}=f(await i.repos.add({accessSourceIds:o}),"Failed to link repositories",r);if(!r)z("Repositories linked.");D(_H,a,{json:r})},DH=async(e)=>{let{values:t,positionals:n}=S(e,kS,{allowPositionals:!0}),r=t.json,o=n[0];if(!o){if(r)return h("Repository is required: pass owner/name or a repository ID from 'sazabi repos list'.");return g("Repository is required: pass owner/name or a repository ID from 'sazabi repos list'.")}let{client:i}=wS(t),a=o;if(!jH.test(o)){let{repos:s}=f(await i.repos.list(),"Couldn't list repositories (check the active project and try again)",r),l=s.filter((u)=>u.linked&&u.fullName.toLowerCase()===o.toLowerCase())[0];if(!l){let u=`Couldn't find a linked repository "${o}". Run 'sazabi repos list' to see linked repositories.`;if(r)return h(u);return g(u)}a=l.id}if(f(await i.repos.remove({id:a}),"Failed to unlink repository",r),r){j({removed:!0});return}z("Repository unlinked.")},fR=q("repos","Manage the repositories linked for code search").withSubcommands({list:v("list","List the repositories available to the project",LH).withOptions(IS).withExamples(["sazabi repos list # Available repositories with linked status","sazabi repos list --json # Include access source IDs for repos add"]).build(),add:v("add","Link repositories to the project for code search",zH).withPositionalArgs("[owner/name...]").withOptions({...IS,"access-source-id":{type:"string",description:"Access source ID from 'sazabi repos list' (repeatable); disambiguates multi-source repositories"}}).withExamples(["sazabi repos add acme/api # Link one repository by name","sazabi repos add acme/api acme/web # Link several","sazabi repos add --access-source-id <id> # Link via a specific access source"]).build(),remove:v("remove","Unlink a repository from the project",DH).withPositionalArgs("<owner/name | repo-id>").withOptions(IS).withExamples(["sazabi repos remove acme/api # Unlink a repository by name","sazabi repos remove <repo-id> # Unlink by repository ID"]).build()}).withExamples(["sazabi repos list # Available repositories","sazabi repos add acme/api # Link a repository","sazabi repos remove acme/api # Unlink a repository"]).build();H();H();te();var CS=(e)=>{process.stderr.write(`${e}
|
|
227
227
|
`)},Hu=async(e)=>{let t=new AbortController,n,r=!1,o=()=>{r=!0,t.abort(),n?.close()};if(process.on("SIGINT",o),!e.json)CS(`Streaming events for ${e.label}. Press Ctrl+C to stop.`);try{if(n=f(await e.open(t.signal),e.errorContext,e.json),r)await n.close();let i=UH(),a=0,s;try{for await(let c of n){if(a+=1,e.json){console.log(JSON.stringify(c));continue}let l=i(c);if(l)En(l)}}catch(c){if(r||c instanceof Error&&c.name==="AbortError")s=void 0;else s=c instanceof Error?c:Error(String(c))}if(s){if(e.json)return h(s.message);en(s.message);return}if($H(n.cursor,e.resumeCommand),!e.json)CS(r?`Interrupted after ${Ft(a,"event")}.`:`Stream ended after ${Ft(a,"event")}.`)}finally{process.removeListener("SIGINT",o)}},$H=(e,t)=>{if(!e)return;CS(`Resume with: ${t} --cursor ${e}`)},yR=160,NH=(e)=>{let t=e.replace(/\s+/g," ").trim();return t.length>yR?`${t.slice(0,yR-3)}...`:t},UH=()=>{let e=new Map;return(t)=>{switch(t.type){case"run_started":return`run started (${t.runId})`;case"message_started":return`message started (${t.messageId})`;case"text_chunk":return;case"text_complete":return`assistant: ${NH(t.content)}`;case"reasoning_progress":return`thinking (~${t.estimatedTokens} tokens)`;case"reasoning_complete":return"thinking done";case"tool_call_pending":return e.set(t.toolCallId,t.name),`tool ${t.name} · pending`;case"tool_call_start":return e.set(t.toolCallId,t.name),`tool ${t.name} · started`;case"tool_call_complete":{let n=e.get(t.toolCallId)??t.toolCallId,r=t.durationMs!==void 0?` (${t.durationMs}ms)`:"";return`tool ${n} · ${t.status}${r}`}case"artifact":return`artifact ${t.name}`;case"error":return`error: ${t.message}`;case"stream_reset":return`stream reset (${t.messageId})`;case"disconnected":return"disconnected";default:return}}};se();te();var MH={id:{label:"ID",type:{kind:"id"}},runId:{label:"Run ID",type:{kind:"id"}},threadId:{label:"Thread ID",type:{kind:"id"}},url:{label:"URL",type:{kind:"string"}},status:{label:"Status",type:{kind:"string"}},completed:{label:"Completed",type:{kind:"boolean"}},messageId:{label:"Message ID",type:{kind:"nullable-string",emptyLabel:"(none)"}},response:{label:"Response",type:{kind:"nullable-string"}},failureClass:{label:"Failure",type:{kind:"nullable-string",emptyLabel:"(none)"}},failureRetryable:{label:"Retryable",type:{kind:"custom",render:(e)=>e==null?Je("(unknown)"):e?"yes":"no",serialize:(e)=>e==null?null:Boolean(e)}}},FH={layout:"sections",schema:MH,primary:{title:"Run",fields:["id","runId","threadId","url","status","completed","messageId","failureClass","failureRetryable"]},secondary:[{title:"Response",field:"response"}]},BH={id:{label:"ID",type:{kind:"id"}},threadId:{label:"Thread ID",type:{kind:"id"}},status:{label:"Status",type:{kind:"string"}},source:{label:"Source",type:{kind:"string"}},createdAt:{label:"Created",type:{kind:"date"}},completedAt:{label:"Completed",type:{kind:"nullable-date",emptyLabel:"(in progress)"}},failureClass:{label:"Failure",type:{kind:"nullable-string",emptyLabel:"(none)"}},failureRetryable:{label:"Retryable",type:{kind:"custom",render:(e)=>e==null?Je("(unknown)"):e?"yes":"no",serialize:(e)=>e==null?null:Boolean(e)}}},GH={schema:BH,columns:["id","threadId","status","source","createdAt","completedAt","failureClass"],jsonFields:["id","threadId","status","source","createdAt","completedAt","failureClass","failureRetryable"],header:"Runs",emptyMessage:"No runs found."},KH=async(e,t={})=>{let n=A({tokenFlag:t.token,jsonMode:t.json}),r=T({token:n.token,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl}),o=f(await r.runs.get(e),"Couldn't get run (check the run ID and try again)",t.json),i=t.wait&&!o.completed?f(await Tu({client:r,runId:e,threadId:o.threadId,timeoutMs:t.timeout,printProgress:!t.json}),"Couldn't get run (check the run ID and try again)",t.json):o,a={...i,id:i.runId,url:Cx(await We({client:r,projectId:n.projectId,jsonMode:t.json}),i.threadId,void 0,i.messageId??void 0)};if(R(FH,a,{json:t.json}),!t.json&&!i.completed)ie(),N(`Poll with: sazabi runs get ${i.runId}`)},qH=async(e={})=>{let t=A({tokenFlag:e.token,jsonMode:e.json}),n=T({token:t.token,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl}),r=f(await n.runs.list({limit:e.limit,cursor:e.cursor}),"Couldn't list runs (check the active project and try again)",e.json),{nextCursor:o}=r,i=r.runs.map((a)=>({id:a.id,threadId:a.threadId,status:a.status,source:a.source,createdAt:a.createdAt,completedAt:a.completedAt,failureClass:a.failureClass,failureRetryable:a.failureRetryable}));if(D(GH,i,{json:e.json,nextCursor:o,contract:{response:r,itemsKey:"runs"}}),!e.json&&o)N(`Next page: sazabi runs list --cursor ${o}`)},WH=async(e,t={})=>{let n=A({tokenFlag:t.token,jsonMode:t.json}),r=T({token:n.token,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl}),o=f(await r.runs.cancel(e),"Failed to cancel run",t.json);if(t.json){j({...o,runId:e});return}z(`Cancellation requested for run ${e}.`),N(`Cancellation is best-effort; poll with: sazabi runs get ${e}`)},VH=async(e,t={})=>{let n=A({tokenFlag:t.token,jsonMode:t.json}),r=T({token:n.token,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl});await Hu({json:t.json,label:`run ${e}`,resumeCommand:`sazabi runs stream ${e}`,errorContext:`Couldn't stream run (retry with 'sazabi runs stream ${e}')`,open:(o)=>r.runs.stream({runId:e,...t.cursor?{cursor:t.cursor}:{},signal:o})})},bR=q("runs","Inspect deferred agent runs").withSubcommands({list:v("list","List runs for the active project",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},limit:{type:"string"},cursor:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0});if(n.length>0){let o=n.join(", ");if(t.json)return h(`Unexpected arguments: ${o}. Run 'sazabi runs -h' for usage.`);return g(`Unexpected arguments: ${o}. Run 'sazabi runs -h' for usage.`)}let r=t.limit?et(t.limit,1,100,"Limit",t.json):void 0;await qH({token:t.token,limit:r,cursor:t.cursor,json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},limit:{type:"string",description:"Maximum number of runs to return (1–100, default 50)"},cursor:{type:"string",description:"Cursor from a previous response to fetch the next page"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi runs list # List recent runs for the active project","sazabi runs list --limit 10 # List the 10 most recent runs","sazabi runs list --json # Output as JSON"]).build(),get:v("get","Get a deferred run by run ID",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},wait:{type:"boolean"},timeout:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Run ID is required. Usage: sazabi runs get <run-id>");return g("Run ID is required. Usage: sazabi runs get <run-id>")}if(n.length>1){let i=n.slice(1).join(", ");if(t.json)return h(`Unexpected arguments: ${i}. Run 'sazabi runs -h' for usage.`);return g(`Unexpected arguments: ${i}. Run 'sazabi runs -h' for usage.`)}let o=t.timeout?et(t.timeout,1,3600,"Timeout",t.json)*1000:void 0;await KH(r,{token:t.token,wait:t.wait,timeout:o,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<run-id>").withOptions({token:{type:"string",description:"Override token"},wait:{type:"boolean",description:"Wait for terminal status and print the final result"},timeout:{type:"string",description:"Timeout in seconds to wait before returning processing state"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi runs get <run-id> # Check current run status","sazabi runs get <run-id> --wait # Wait until the run is terminal","sazabi runs get <run-id> --wait --timeout 60 # Wait up to 60 seconds","sazabi runs get <run-id> --json # Output run state as JSON"]).build(),cancel:v("cancel","Request cancellation of an in-flight run",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Run ID is required. Usage: sazabi runs cancel <run-id>");return g("Run ID is required. Usage: sazabi runs cancel <run-id>")}if(n.length>1){let o=n.slice(1).join(", ");if(t.json)return h(`Unexpected arguments: ${o}. Run 'sazabi runs -h' for usage.`);return g(`Unexpected arguments: ${o}. Run 'sazabi runs -h' for usage.`)}await WH(r,{token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<run-id>").withOptions({token:{type:"string",description:"Override token"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi runs cancel <run-id> # Request cancellation of a run","sazabi runs cancel <run-id> --json # Output the result as JSON"]).build(),stream:v("stream","Stream a run's agent events in real time",async(e)=>{let{values:t,positionals:n}=S(e,{token:{type:"string"},cursor:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Run ID is required. Usage: sazabi runs stream <run-id>");return g("Run ID is required. Usage: sazabi runs stream <run-id>")}if(n.length>1){let o=n.slice(1).join(", ");if(t.json)return h(`Unexpected arguments: ${o}. Run 'sazabi runs -h' for usage.`);return g(`Unexpected arguments: ${o}. Run 'sazabi runs -h' for usage.`)}await VH(r,{token:t.token,cursor:t.cursor,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<run-id>").withOptions({token:{type:"string",description:"Override token"},cursor:{type:"string",description:"Resume from a prior stream cursor after a disconnect"},json:{type:"boolean",description:"Emit one NDJSON event per line (stdout carries events only)"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi runs stream <run-id> # Follow run events (human-readable)","sazabi runs stream <run-id> --json # Emit NDJSON events for tools","sazabi runs stream <run-id> --cursor seq:42 # Resume after a disconnect"]).build()}).withExamples(["sazabi runs list # List recent runs for the active project","sazabi runs get <run-id> # Check current run status","sazabi runs get <run-id> --wait # Wait until the run is terminal","sazabi runs cancel <run-id> # Request cancellation of a run","sazabi runs stream <run-id> # Stream run events in real time"]).build();H();import{readFile as vR}from"node:fs/promises";se();te();var HH={type:{label:"Type",type:{kind:"string"}},label:{label:"Name",type:{kind:"string"}},envVars:{label:"Env vars",type:{kind:"string"}},hasSetupSkill:{label:"Setup skill",type:{kind:"boolean"}},url:{label:"URL",type:{kind:"string"}}},ZH={schema:HH,columns:["type","label","envVars","hasSetupSkill","url"],header:"Browse sandbox CLIs",emptyMessage:"No sandbox CLIs available. Try again later."},SR={cliType:{label:"Type",type:{kind:"string"}},credentialSource:{label:"Credential source",type:{kind:"string"}},isSystemManaged:{label:"System managed",type:{kind:"boolean"}},fallbackConfigured:{label:"Fallback configured",type:{kind:"boolean"}},envVarKeys:{label:"Env vars",type:{kind:"custom",render:(e)=>Array.isArray(e)&&e.length>0?e.join(", "):"(none)",serialize:(e)=>e}},url:{label:"URL",type:{kind:"string"}}},JH={schema:SR,columns:["cliType","credentialSource","isSystemManaged","fallbackConfigured","envVarKeys","url"],header:"Connected sandbox CLIs",emptyMessage:"No CLI connections configured. Run 'sazabi sandbox-clis types' to see available sandbox CLIs."},YH={layout:"field-list",schema:SR,fields:["cliType","credentialSource","isSystemManaged","fallbackConfigured","envVarKeys","url"],title:"CLI connection"},XH={type:{label:"Type",type:{kind:"string"}},setupSkill:{label:"Setup skill",type:{kind:"string"}}},QH={layout:"field-list",schema:XH,fields:["type","setupSkill"],title:"Sandbox CLI setup skill"},eZ={projectId:{label:"Project ID",type:{kind:"id"}},cliType:{label:"Type",type:{kind:"string"}},envVarKeys:{label:"Env vars",type:{kind:"custom",render:(e)=>Array.isArray(e)&&e.length>0?e.join(", "):"(none)",serialize:(e)=>e}}},tZ={layout:"field-list",schema:eZ,fields:["projectId","cliType","envVarKeys"],title:"CLI connection"},nZ={projectId:{label:"Project ID",type:{kind:"id"}},cliType:{label:"Type",type:{kind:"string"}},deleted:{label:"Deleted",type:{kind:"boolean"}}},oZ={layout:"field-list",schema:nZ,fields:["projectId","cliType","deleted"],title:"CLI connection"},rZ={status:{label:"Status",type:{kind:"string"}},message:{label:"Message",type:{kind:"nullable-string"}},stdout:{label:"Standard output",type:{kind:"string"}},stderr:{label:"Standard error",type:{kind:"string"}}},IR={layout:"field-list",schema:rZ,fields:["status","message","stdout","stderr"],title:"CLI connection test"},ar=(e)=>{let t=e.json,n=A({tokenFlag:e.token,jsonMode:t}),r=e["api-base-url"];return{client:T({token:n.token,organizationId:n.organizationId,projectId:n.projectId,apiBaseUrlFlag:r,jsonMode:t}),json:t,projectId:n.projectId,apiBaseUrl:r}},mn=(e,t)=>{if(t)return h(e);return g(e)},kR=async()=>{let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(t));return Buffer.concat(e).toString("utf8")},iZ=async(e)=>{if(e.startsWith("@@"))return e.slice(1);if(!e.startsWith("@"))return e;let t=e.slice(1);if(!t)throw Error("An @ value must name a file or use @- for standard input.");return t==="-"?kR():vR(t,"utf8")},wR=async(e,t)=>{let n=new Map,r=e["env-file"],o=e.env,i=typeof o==="string"?[o]:Array.isArray(o)?o:[];if((r==="-"?1:0)+i.filter((s)=>{let c=s.indexOf("=");return c>=1&&s.slice(c+1)==="@-"}).length>1)mn("Standard input can only be used once; choose either --env-file - or one KEY=@- value.",t);if(r){let s;try{let c=r==="-"?await kR():await vR(r,"utf8");s=JSON.parse(c)}catch(c){mn(`Couldn't read --env-file (${c instanceof Error?c.message:String(c)}).`,t)}if(!s||typeof s!=="object"||Array.isArray(s)||Object.values(s).some((c)=>typeof c!=="string"))mn("--env-file must contain a JSON object of string values.",t);for(let[c,l]of Object.entries(s))n.set(c,l)}for(let s of i){let c=s.indexOf("=");if(c<1)mn(`Invalid --env value '${s}'. Use KEY=VALUE or KEY=@file.`,t);let l=s.slice(0,c);if(n.has(l))mn(`Environment variable '${l}' was provided more than once.`,t);try{n.set(l,await iZ(s.slice(c+1)))}catch(u){mn(`Couldn't read value for '${l}' (${u instanceof Error?u.message:String(u)}).`,t)}}if(n.size===0)mn("Provide credentials with --env or --env-file.",t);return[...n].map(([s,c])=>({key:s,value:c}))},PS=(e,t)=>{let n=e.type;if(!n)return mn("--type is required. Use 'sazabi sandbox-clis types' to see available sandbox CLI types.",t);return n},aZ=async(e)=>{let{values:t}=S(e,{...O}),{client:n,json:r,projectId:o}=ar(t),i=f(await n.sandboxClis.listTypes(),"Couldn't list sandbox CLI types (check your token and try again)",r),a=await We({client:n,projectId:o,jsonMode:r}),s=i.types.map((c)=>({type:c.type,label:c.label,envVars:c.envVarKeys.length>0?c.envVarKeys.join(", "):"(none)",hasSetupSkill:Boolean(c.setupSkill),url:ql(a,c.type)}));D(ZH,s,{json:r,contract:{response:i,itemsKey:"types"}})},sZ=async(e)=>{let{values:t}=S(e,{...O,"project-id":{type:"string"}}),{client:n,json:r,projectId:o}=ar(t),i=await We({client:n,projectId:t["project-id"]??o,jsonMode:r}),{connections:a}=f(await n.sandboxClis.listConnections({projectId:i}),"Couldn't list CLI connections (check your token and project, then try again)",r);D(JH,a.map((s)=>({...s,url:ql(i,s.cliType)})),{json:r})},cZ=async(e)=>{let{values:t,positionals:n}=S(e,{...O,"project-id":{type:"string"}},{allowPositionals:!0}),{client:r,json:o,projectId:i}=ar(t),a=n[0];if(!a)return mn("CLI type is required. Use 'sazabi sandbox-clis types' to see available sandbox CLI types.",o);if(n.length>1){let u=n.slice(1).join(", ");return mn(`Unexpected arguments: ${u}. Usage: sazabi sandbox-clis get <type>`,o)}let s=await We({client:r,projectId:t["project-id"]??i,jsonMode:o}),{connections:c}=f(await r.sandboxClis.listConnections({projectId:s}),"Couldn't get the CLI connection (check your token and project, then try again)",o),l=c.find((u)=>u.cliType===a);if(!l)return mn(`No CLI connection found for '${a}'. Run 'sazabi sandbox-clis list' to see connected sandbox CLIs.`,o);R(YH,{...l,url:ql(s,l.cliType)},{json:o})},lZ=async(e)=>{let{values:t}=S(e,{...O,env:{type:"string",multiple:!0},"env-file":{type:"string"},"project-id":{type:"string"},"skip-test":{type:"boolean"},type:{type:"string"}}),{client:n,json:r,projectId:o}=ar(t),i=PS(t,r),a=await wR(t,r),s=t["project-id"]??o??void 0;if(!t["skip-test"]){if(!r)N("Testing credentials before saving...");let l=f(await n.sandboxClis.test({projectId:s,cliType:i,environmentVariables:a}),"Couldn't run the connection test, so nothing was saved. Re-run with --skip-test to store without testing.",r);if(l.status==="failed"){if(r)return h({code:"CLI_ERROR",message:l.message??"The credentials failed the connection test; nothing was saved. Re-run with --skip-test to store anyway.",operationId:null,test:l});return R(IR,l,{json:r}),g("The credentials failed the connection test; nothing was saved. Re-run with --skip-test to store anyway.")}if(!r)z("Connection test passed.")}let c=f(await n.sandboxClis.upsert({projectId:s,cliType:i,environmentVariables:a}),"Failed to save CLI connection. Check the credentials, then try again.",r);if(!r)z("CLI connection saved.");R(tZ,c,{json:r})},uZ=async(e)=>{let{values:t}=S(e,{...O,"project-id":{type:"string"},type:{type:"string"}}),{client:n,json:r,projectId:o}=ar(t),i=PS(t,r),a=f(await n.sandboxClis.delete({projectId:t["project-id"]??o??void 0,cliType:i}),"Failed to disconnect the sandbox CLI. Check your token and project, then try again.",r);if(!r)z(a.deleted?"Sandbox CLI disconnected.":"No stored CLI connection was configured.");R(oZ,a,{json:r})},dZ=async(e)=>{let{values:t}=S(e,{...O,env:{type:"string",multiple:!0},"env-file":{type:"string"},"project-id":{type:"string"},type:{type:"string"}}),{client:n,json:r,projectId:o}=ar(t),i=PS(t,r),a=await wR(t,r),s=f(await n.sandboxClis.test({projectId:t["project-id"]??o??void 0,cliType:i,environmentVariables:a}),"Failed to test CLI connection. Check your token, then try again.",r);if(R(IR,s,{json:r}),s.status==="failed")process.exitCode=1},pZ=async(e)=>{let{values:t}=S(e,{...O,type:{type:"string"}});if(!t.type){if(t.json)return h("--type is required. Use 'sazabi sandbox-clis types' to see available sandbox CLI types.");return g("--type is required. Use 'sazabi sandbox-clis types' to see available sandbox CLI types.")}let{client:n,json:r}=ar(t),{types:o}=f(await n.sandboxClis.listTypes(),"Couldn't list sandbox CLI types (check your token and try again)",r),i=o.find((a)=>a.type===t.type);if(!i){let a=`Unknown sandbox CLI type: ${t.type}. Run 'sazabi sandbox-clis types' to see available types.`;if(r)return h(a);return g(a)}if(!i.setupSkill){let a=`No setup skill available for ${t.type}. This sandbox CLI does not have an agent-ready skill yet.`;if(r)return h(a);return g(a)}R(QH,{type:t.type,setupSkill:i.setupSkill},{json:r})},CR=q("sandbox-clis","Manage sandbox CLIs").withSubcommands({list:v("list","List connected sandbox CLIs",sZ).withOptions({...x,"project-id":{type:"string",description:"Project ID"}}).withExamples(["sazabi sandbox-clis list # List connected sandbox CLIs","sazabi sandbox-clis list --json # Output as JSON"]).build(),get:v("get","Get one CLI connection",cZ).withPositionalArgs("<type>").withOptions({...x,"project-id":{type:"string",description:"Project ID"}}).withExamples(["sazabi sandbox-clis get aws # Show the AWS CLI connection","sazabi sandbox-clis get github --json # Output as JSON"]).build(),connect:v("connect","Connect a sandbox CLI, or replace its credentials",lZ).withOptions({...x,env:{type:"string",multiple:!0,description:"Repeat KEY=VALUE; use KEY=@file or KEY=@@value for a literal @"},"env-file":{type:"string",description:"JSON object containing credential names and values"},"project-id":{type:"string",description:"Project ID"},"skip-test":{type:"boolean",description:"Save without running the connection test first"},type:{type:"string",description:"Sandbox CLI type"}}).withExamples(["sazabi sandbox-clis connect --type github --env GH_TOKEN=@token.txt # Test, then save credentials","sazabi sandbox-clis connect --type aws --env-file credentials.json # Read credentials from JSON","sazabi sandbox-clis connect --type aws --env-file creds.json --skip-test # Save without testing"]).build(),disconnect:v("disconnect","Disconnect a stored sandbox CLI",uZ).withOptions({...x,"project-id":{type:"string",description:"Project ID"},type:{type:"string",description:"Sandbox CLI type"}}).withExamples(["sazabi sandbox-clis disconnect --type aws # Disconnect the AWS CLI"]).build(),test:v("test","Test sandbox CLI credentials without saving",dZ).withOptions({...x,env:{type:"string",multiple:!0,description:"Repeat KEY=VALUE; use KEY=@file or KEY=@@value for a literal @"},"env-file":{type:"string",description:"JSON object containing credential names and values"},"project-id":{type:"string",description:"Project ID"},type:{type:"string",description:"Sandbox CLI type"}}).withExamples(["sazabi sandbox-clis test --type github --env GH_TOKEN=@token.txt # Validate credentials"]).build(),types:v("types","List available sandbox CLI types",aZ).withOptions({...x}).withExamples(["sazabi sandbox-clis types # List all sandbox CLI types","sazabi sandbox-clis types --json # Output as JSON"]).build(),skill:v("skill","Show setup skill for a sandbox CLI type",pZ).withOptions({...x,type:{type:"string",description:"Sandbox CLI type (e.g. aws, github, vercel, supabase)"}}).withExamples(["sazabi sandbox-clis skill --type aws # Show AWS setup skill","sazabi sandbox-clis skill --type github # Show GitHub setup skill","sazabi sandbox-clis skill --type vercel --json # Output as JSON"]).build()}).withExamples(["sazabi sandbox-clis list # List connected sandbox CLIs","sazabi sandbox-clis types # List available sandbox CLIs","sazabi sandbox-clis connect --type aws --env-file credentials.json # Save a connection","sazabi sandbox-clis skill --type aws # Show setup skill"]).build();H();import{readFile as mZ}from"node:fs/promises";se();te();var Ju=(e)=>({id:e.id,projectId:e.projectId,name:e.name,description:e.description,contentHash:e.contentHash,content:"content"in e?e.content:null,createdAt:e.createdAt,updatedAt:e.updatedAt}),PR={id:{label:"ID",type:{kind:"id"}},projectId:{label:"Project ID",type:{kind:"id"}},name:{label:"Name",type:{kind:"string"}},description:{label:"Description",type:{kind:"nullable-string"}},contentHash:{label:"Content hash",type:{kind:"nullable-string"}},content:{label:"Content",type:{kind:"custom",render:(e)=>e?String(e):"(empty)",serialize:(e)=>e}},createdAt:{label:"Created at",type:{kind:"nullable-date"}},updatedAt:{label:"Updated at",type:{kind:"nullable-date"}}},gZ={schema:PR,columns:["name","description","updatedAt"],jsonFields:["id","projectId","name","description","updatedAt"],header:"Scripts",emptyMessage:"No scripts found."},OS={layout:"field-list",schema:PR,fields:["id","projectId","name","description","contentHash","content","createdAt","updatedAt"],title:"Script"},Cs=(e)=>{let t=A({tokenFlag:e.token,projectIdFlag:e.projectId,jsonMode:e.json});return{client:T({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:e.json})}},hZ=async()=>{let e=[];process.stdin.setEncoding("utf8");for await(let t of process.stdin)e.push(String(t));return e.join("")},OR=async(e,t,n)=>{let r=e.content!==void 0,o=e.file!==void 0;if(r&&o){if(t){h("Provide script content via exactly one of --content or --file.");return}g("Provide script content via exactly one of --content or --file.");return}if(!r&&!o){if(!n)return;let a="Script content is required. Provide --content <text> or --file <path>.";if(t){h(a);return}g(a);return}if(r)return e.content;let i=e.file;try{return i==="-"?await hZ():await mZ(i,"utf8")}catch(a){let s=`Couldn't read script content (check that the --file path exists and is readable): ${a instanceof Error?a.message:String(a)}`;if(t){h(s);return}g(s);return}},fZ=async(e)=>{let{client:t}=Cs(e),n=f(await t.scripts.list({search:e.search,limit:e.limit,cursor:e.cursor}),"Couldn't list scripts (check the active project and try again)",e.json);D(gZ,n.scripts.map(Ju),{json:e.json,nextCursor:n.nextCursor,contract:{response:n,itemsKey:"scripts"}})},yZ=async(e,t)=>{let{client:n}=Cs(t),r=f(await n.scripts.get(e),"Couldn't get script (run 'sazabi scripts list' to see script names)",t.json);R(OS,Ju(r.script),{json:t.json,contract:r.script})},bZ=async(e,t)=>{let n=await OR(t,t.json,!0);if(n===void 0)return;let{client:r}=Cs(t),o=f(await r.scripts.create({name:e,content:n,...t.description!==void 0?{description:t.description}:{}}),"Couldn't create script (check the script name and content, then try again)",t.json);if(!t.json)z(`Script "${o.script.name}" created.`);R(OS,Ju(o.script),{json:t.json,contract:o.script})},vZ=async(e,t)=>{let n=t.description!==void 0||t.clearDescription===!0;if(t.description!==void 0&&t.clearDescription===!0){if(t.json){h("Use either --description or --clear-description, not both.");return}g("Use either --description or --clear-description, not both.");return}let r=await OR(t,t.json,!1);if(r===void 0&&t.content!==void 0)return;if(r===void 0&&t.file!==void 0)return;if(r===void 0&&!n){if(t.json){h("Nothing to update. Provide --content, --file, --description, or --clear-description.");return}g("Nothing to update. Provide --content, --file, --description, or --clear-description.");return}let{client:o}=Cs(t),i=f(await o.scripts.update(e,{...r!==void 0?{content:r}:{},...t.clearDescription?{description:null}:t.description!==void 0?{description:t.description}:{}}),"Couldn't update script (run 'sazabi scripts list' to see script names)",t.json);if(!t.json)z(`Script "${i.script.name}" updated.`);R(OS,Ju(i.script),{json:t.json,contract:i.script})},SZ=async(e,t)=>{let{client:n}=Cs(t);if(f(await n.scripts.delete(e),"Couldn't delete script (run 'sazabi scripts list' to see script names)",t.json),t.json){j({deleted:!0,name:e});return}z(`Script "${e}" deleted.`)},ks={...O,"project-id":{type:"string"}},ws={...x,"project-id":{type:"string",description:"Override active project ID"}},Zu=(e,t)=>{let n=e[0];if(!n){if(t){h("Script name is required.");return}g("Script name is required.");return}return n},xR=q("scripts","Manage durable project scripts").withSubcommands({list:v("list","List scripts in the active project",async(e)=>{let{values:t}=S(e,{...ks,search:{type:"string"},limit:{type:"string"},cursor:{type:"string"}}),n=(o)=>{if(t.json){h(o);return}g(o)},r;if(t.limit!==void 0){if(r=Number(t.limit),!Number.isInteger(r)||r<1||r>100)return n(`Invalid --limit value "${t.limit}". Expected an integer between 1 and 100.`)}await fZ({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],search:t.search,limit:r,cursor:t.cursor})}).withOptions({...ws,search:{type:"string",description:"Filter by script name (case-insensitive)"},limit:{type:"string",description:"Maximum number of scripts to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from previous response"}}).withExamples(["sazabi scripts list # List project scripts","sazabi scripts list --search deploy # Search scripts by name"]).build(),get:v("get","Get one project script by name",async(e)=>{let{values:t,positionals:n}=S(e,ks,{allowPositionals:!0}),r=Zu(n,t.json);if(!r)return;await yZ(r,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<name>").withOptions(ws).withExamples(["sazabi scripts get deploy # Get one script"]).build(),create:v("create","Create a project script",async(e)=>{let{values:t,positionals:n}=S(e,{...ks,content:{type:"string"},file:{type:"string"},description:{type:"string"}},{allowPositionals:!0}),r=Zu(n,t.json);if(!r)return;await bZ(r,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],content:t.content,file:t.file,description:t.description})}).withPositionalArgs("<name>").withOptions({...ws,content:{type:"string",description:"Script body text"},file:{type:"string",description:"Read script body from a file, or '-' for stdin"},description:{type:"string",description:"Optional human-readable description"}}).withExamples(["sazabi scripts create deploy --content '#!/usr/bin/env bash' # Create from inline content","sazabi scripts create deploy --file ./deploy.sh # Create from a file"]).build(),update:v("update","Update a project script",async(e)=>{let{values:t,positionals:n}=S(e,{...ks,content:{type:"string"},file:{type:"string"},description:{type:"string"},"clear-description":{type:"boolean"}},{allowPositionals:!0}),r=Zu(n,t.json);if(!r)return;await vZ(r,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],content:t.content,file:t.file,description:t.description,clearDescription:t["clear-description"]})}).withPositionalArgs("<name>").withOptions({...ws,content:{type:"string",description:"New script body text"},file:{type:"string",description:"Read new script body from a file, or '-' for stdin"},description:{type:"string",description:"New human-readable description"},"clear-description":{type:"boolean",description:"Clear the script description"}}).withExamples(["sazabi scripts update deploy --description 'Deploy helper' # Update description only","sazabi scripts update deploy --file ./deploy.sh # Replace script body"]).build(),delete:v("delete","Delete a project script",async(e)=>{let{values:t,positionals:n}=S(e,ks,{allowPositionals:!0}),r=Zu(n,t.json);if(!r)return;await SZ(r,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<name>").withOptions(ws).withExamples(["sazabi scripts delete deploy # Delete a script"]).build()}).withExamples(["sazabi scripts list # List project scripts","sazabi scripts get deploy # Get one script","sazabi scripts create deploy --file ./deploy.sh # Create a script","sazabi scripts update deploy --description 'Deploy helper' # Update a script","sazabi scripts delete deploy # Delete a script"]).build();H();te();Qe();var xS=["apiBaseUrl","authBaseUrl","webBaseUrl","intakeBaseUrl","tailBaseUrl","apiDomain","webDomain","intakeDomain","tailDomain","forwardPublicKey"],AR=(e)=>xS.includes(e),IZ=["apiBaseUrl","authBaseUrl","webBaseUrl","intakeBaseUrl","tailBaseUrl"],kZ=(e)=>IZ.includes(e),wZ={apiBaseUrl:["http:","https:"],authBaseUrl:["http:","https:"],webBaseUrl:["http:","https:"],intakeBaseUrl:["http:","https:"],tailBaseUrl:["ws:","wss:","http:","https:"]},CZ=(e,t)=>{let n=(()=>{try{return new URL(t)}catch{return null}})();if(!n)return we(`Invalid URL for ${e}: '${t}'. Provide a full URL such as https://api.example.com.`);let r=wZ[e];if(!r.includes(n.protocol))return we(`Invalid protocol '${n.protocol}' for ${e}. Allowed: ${r.join(", ")}.`);return Re(n.toString().replace(/\/+$/,""))},PZ=new Set(["token"]),OZ=(e)=>{let t={...e};for(let n of PZ)delete t[n];return t},xZ=(e={})=>{let t=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",e.json),n=Ht(t),r=f(dt(t),"Couldn't resolve profile (run 'sazabi profiles list' to see available profiles)",e.json),o=OZ(r);if(e.json){j({success:!0,settingsFile:ei,profile:n,settings:o});return}he({"Settings file":ei,"Active profile":n}),ie();let i=Object.entries(o).filter(([,s])=>s!=null);if(i.length===0){xo("No settings configured.");return}let a=i.map(([s,c])=>({key:s,value:String(c)})).sort((s,c)=>s.key.localeCompare(c.key));Mi(a,[{header:"Key",key:"key",width:20},{header:"Value",key:"value"}],{header:"Settings"})},AZ=(e,t,n={})=>{if(!AR(e)){let c=xS.join(", "),l=`Invalid setting key: '${e}'. Valid keys: ${c}.`;if(n.json){h(l);return}g(l);return}let r=t;if(kZ(e)){let c=CZ(e,t);if(!c.success){if(n.json){h(c.error);return}g(c.error);return}r=c.value}let o=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",n.json),i=f(dt(o),"Couldn't resolve profile (run 'sazabi profiles list' to see available profiles)",n.json);if(e==="forwardPublicKey"&&!i.activeProjectId){if(n.json){h("Cannot set forwardPublicKey without an active project. Select a project first with 'sazabi projects use <id>'.");return}g("Cannot set forwardPublicKey without an active project. Select a project first with 'sazabi projects use <id>'.");return}let a=e==="forwardPublicKey"?{forwardPublicKey:r,forwardPublicKeyProjectId:i.activeProjectId}:{[e]:r},s=f(pt(o,a),"Failed to update profile",n.json);if(f(Ne(s),"Failed to write settings",n.json),n.json){j({success:!0,key:e,value:r});return}z(`Set ${e} to ${r}.`)},TZ=(e,t={})=>{if(!AR(e)){let a=xS.join(", "),s=`Invalid setting key: '${e}'. Valid keys: ${a}.`;if(t.json){h(s);return}g(s);return}let n=f(Oe(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t.json),r=f(dt(n),"Couldn't resolve profile (run 'sazabi profiles list' to see available profiles)",t.json),o=e==="forwardPublicKey"?Zt(r):{[e]:void 0},i=f(pt(n,o),"Failed to update profile",t.json);if(f(Ne(i),"Failed to write settings",t.json),t.json){j({success:!0,key:e});return}z(`Cleared ${e}.`)},TR=q("settings","Manage global CLI settings").withSubcommands({view:v("view","Show current CLI settings and file location",async(e)=>{let{values:t}=S(e,{json:{type:"boolean"}});xZ({json:t.json})}).withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(["sazabi settings view # Show current settings","sazabi settings view --json # Output as JSON"]).build(),set:v("set","Set a global configuration value",async(e)=>{let{values:t,positionals:n}=S(e,{json:{type:"boolean"}},{allowPositionals:!0}),r=n[0],o=n[1];if(!r){if(t.json)return h("Setting key is required. Usage: sazabi settings set <key> <value>");return g("Setting key is required. Usage: sazabi settings set <key> <value>")}if(!o){if(t.json)return h("Value is required. Usage: sazabi settings set <key> <value>");return g("Value is required. Usage: sazabi settings set <key> <value>")}AZ(r,o,{json:t.json})}).withPositionalArgs("<key> <value>").withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(["sazabi settings set apiBaseUrl https://api.example.com # Override a base URL (also: authBaseUrl, webBaseUrl, intakeBaseUrl, tailBaseUrl)"]).build(),unset:v("unset","Clear a global configuration value",async(e)=>{let{values:t,positionals:n}=S(e,{json:{type:"boolean"}},{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Setting key is required. Usage: sazabi settings unset <key>");return g("Setting key is required. Usage: sazabi settings unset <key>")}TZ(r,{json:t.json})}).withPositionalArgs("<key>").withOptions({json:{type:"boolean",description:"Output as JSON"}}).withExamples(["sazabi settings unset apiBaseUrl # Clear API base URL override","sazabi settings unset --json apiBaseUrl # Output as JSON"]).build()}).withExamples(["sazabi settings view # Show current settings","sazabi settings set apiBaseUrl https://api.example.com # Set API base URL","sazabi settings unset apiBaseUrl # Clear API base URL override"]).build();H();se();te();var ER=["done","not-done","skipped"],_Z={done:"done","not-done":"not done",skipped:"skipped"},jZ=(e)=>ER.includes(e),RZ=(e)=>{switch(e.status??(e.completed?"complete":e.skipped?"skipped":"incomplete")){case"complete":return"done";case"skipped":return"skipped";default:return"not done"}},EZ=(e)=>e.list==="getting-started",LZ=(e)=>({...e,state:RZ(e)}),LR=({state:e,...t})=>t,zR={id:{label:"ID",type:{kind:"id"}},label:{label:"Label",type:{kind:"string"}},state:{label:"Status",type:{kind:"string"}},status:{label:"Wire status",type:{kind:"string"}},completedAt:{label:"Completed",type:{kind:"nullable-date"}},completed:{label:"Completed?",type:{kind:"boolean"}},skipped:{label:"Skipped?",type:{kind:"boolean"}},description:{label:"Description",type:{kind:"string"}},instructions:{label:"Instructions",type:{kind:"string"}},category:{label:"Category",type:{kind:"string"}},list:{label:"List",type:{kind:"string"}},skippable:{label:"Skippable",type:{kind:"boolean"}}},DR=["id","label","description","instructions","completed","completedAt","skipped","category","list","skippable","status"],_R={schema:zR,columns:["id","label","state"],jsonFields:DR,header:"Setup tasks",emptyMessage:"No setup tasks found."},zZ=["id","label","state","description","instructions"],DZ=(e)=>({layout:"field-list",schema:zR,title:"Setup task",fields:e?DR:zZ}),$R=async(e)=>{let t=A({tokenFlag:e.token,projectIdFlag:e.projectId,organizationIdFlag:e.organizationId,jsonMode:e.json}),n=T({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:e.json});await We({client:n,projectId:t.projectId,jsonMode:e.json});let r=f(await n.tasks.list(),"Couldn't list setup tasks (check the active project and try again)",e.json);return{tasks:r.tasks.filter(EZ).map(LZ),knownIds:new Set(r.tasks.map((o)=>o.id))}},$Z=async(e)=>{let t=e.status;if(t!==void 0&&!jZ(t)){let i=`Invalid --status "${t}". Must be one of: ${ER.join(", ")}.`;if(e.json)return h(i);return g(i)}let{tasks:n}=await $R(e),r=t?_Z[t]:void 0,o=r?n.filter((i)=>i.state===r):n;D({..._R,emptyMessage:r?`No setup tasks with status "${r}".`:_R.emptyMessage},o,{json:e.json,contract:{response:{tasks:o.map(LR)},itemsKey:"tasks"}})},NZ=async(e,t)=>{let{tasks:n,knownIds:r}=await $R(t),o=n.find((i)=>i.id===e);if(!o){let i=r.has(e)?`${e} isn't a setup task; it's an onboarding step. Run 'sazabi onboarding progress ${e}' for its detail, or 'sazabi setup-tasks list' to see the setup tasks.`:`${e} isn't a setup task. Run 'sazabi setup-tasks list' to see them.`;if(t.json)return h(i);return g(i)}R(DZ(Boolean(t.json)),o,{json:t.json,contract:LR(o)})},jR={...O,"project-id":{type:"string"},"organization-id":{type:"string"}},RR={...x,"project-id":{type:"string",description:"Override active project ID"},"organization-id":{type:"string",description:"Override active organization ID"}},NR=q("setup-tasks","Track the setup tasks for the active project").withSubcommands({list:v("list","List the setup tasks with their status",async(e)=>{let{values:t}=S(e,{...jR,status:{type:"string"}});await $Z({token:t.token,projectId:t["project-id"],organizationId:t["organization-id"],apiBaseUrl:t["api-base-url"],json:t.json,status:t.status})}).withOptions({...RR,status:{type:"string",description:"Filter by status: done, not-done, or skipped"}}).withExamples(["sazabi setup-tasks list # Every setup task with its status","sazabi setup-tasks list --status not-done # Only the tasks still to do","sazabi setup-tasks list --json # Output as JSON"]).build(),get:v("get","Show one setup task",async(e)=>{let{values:t,positionals:n}=S(e,jR,{allowPositionals:!0}),r=n[0];if(!r){if(t.json)return h("Task ID is required. Run 'sazabi setup-tasks list' to see the setup tasks.");return g("Task ID is required. Run 'sazabi setup-tasks list' to see the setup tasks.")}await NZ(r,{token:t.token,projectId:t["project-id"],organizationId:t["organization-id"],apiBaseUrl:t["api-base-url"],json:t.json})}).withPositionalArgs("<task-id>").withOptions(RR).withExamples(["sazabi setup-tasks get invite_team # One task in detail","sazabi setup-tasks get connect_log_sources --json # Output as JSON"]).build()}).withExamples(["sazabi setup-tasks list # Every setup task with its status","sazabi setup-tasks list --status not-done # Only the tasks still to do","sazabi setup-tasks get invite_team # One task in detail"]).build();H();se();te();var xs=(e)=>({id:e.id,projectId:e.projectId,name:e.name,expression:e.expression,enabled:e.enabled,compiledVersion:e.compiledVersion,linkedAutomationIds:e.linkedAutomationIds??[],createdAt:e.createdAt,updatedAt:e.updatedAt}),UR={id:{label:"ID",type:{kind:"id"}},projectId:{label:"Project ID",type:{kind:"id"}},name:{label:"Name",type:{kind:"string"}},expression:{label:"Expression",type:{kind:"string"}},enabled:{label:"Enabled",type:{kind:"custom",render:(e)=>e?"Yes":"No",serialize:(e)=>e}},compiledVersion:{label:"Compiled version",type:{kind:"number"}},linkedAutomationIds:{label:"Linked automations",type:{kind:"custom",render:(e)=>Array.isArray(e)&&e.length>0?e.join(", "):"(none)",serialize:(e)=>e}},createdAt:{label:"Created at",type:{kind:"nullable-date"}},updatedAt:{label:"Updated at",type:{kind:"nullable-date"}}},UZ={schema:UR,columns:["name","enabled","updatedAt"],jsonFields:["id","projectId","name","expression","enabled","compiledVersion","linkedAutomationIds","updatedAt"],header:"Signal definitions",emptyMessage:"No signal definitions found."},Yu={layout:"field-list",schema:UR,fields:["id","projectId","name","expression","enabled","compiledVersion","linkedAutomationIds","createdAt","updatedAt"],title:"Signal definition"},Ps={...x,"project-id":{type:"string",description:"Override active project ID"}},Os={...O,"project-id":{type:"string"}},As=(e)=>{let t=A({tokenFlag:e.token,projectIdFlag:e.projectId,jsonMode:e.json});return{client:T({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:e.apiBaseUrl,jsonMode:e.json})}},AS=(e,t)=>{let n=e[0]?.trim();if(!n){if(t){h("Expression ID is required.");return}g("Expression ID is required.");return}return n},MZ=(e,t)=>{let n=e[0]?.trim();if(!n){if(t){h("Expression name is required.");return}g("Expression name is required.");return}return n},FZ=async(e)=>{let{client:t}=As(e),n=f(await t.signalDefinitions.list(),"Couldn't list signal definitions",e.json);D(UZ,n.signalDefinitions.map(xs),{json:e.json,contract:{response:n,itemsKey:"signalDefinitions"}})},BZ=async(e,t)=>{let{client:n}=As(t),r=f(await n.signalDefinitions.get(e),"Couldn't get signal definition (run 'sazabi signal-definitions list' to see IDs)",t.json);R(Yu,xs(r.signalDefinition),{json:t.json,contract:r.signalDefinition})},GZ=async(e,t)=>{if(!t.expression?.trim()){if(t.json){h("CEL expression is required. Pass --expression '<CEL>'.");return}g("CEL expression is required. Pass --expression '<CEL>'.");return}if(t.enabled===!0&&t.disabled===!0){if(t.json){h("Use either --enabled or --disabled, not both.");return}g("Use either --enabled or --disabled, not both.");return}let n=t.disabled===!0?!1:t.enabled===!0?!0:void 0,{client:r}=As(t),o=f(await r.signalDefinitions.create({name:e,expression:t.expression,...n!==void 0?{enabled:n}:{}}),"Couldn't create signal definition",t.json);if(!t.json)z(`Signal definition "${o.signalDefinition.name}" created.`);R(Yu,xs(o.signalDefinition),{json:t.json,contract:o.signalDefinition})},KZ=async(e,t)=>{if(t.name===void 0&&t.expression===void 0&&t.enable!==!0&&t.disable!==!0){if(t.json){h("Nothing to update. Provide --name, --expression, --enable, or --disable.");return}g("Nothing to update. Provide --name, --expression, --enable, or --disable.");return}if(t.enable===!0&&t.disable===!0){if(t.json){h("Use either --enable or --disable, not both.");return}g("Use either --enable or --disable, not both.");return}let n=t.disable===!0?!1:t.enable===!0?!0:void 0,{client:r}=As(t),o=f(await r.signalDefinitions.update(e,{...t.name!==void 0?{name:t.name}:{},...t.expression!==void 0?{expression:t.expression}:{},...n!==void 0?{enabled:n}:{}}),"Couldn't update signal definition",t.json);if(!t.json)z(`Signal definition "${o.signalDefinition.name}" updated.`);R(Yu,xs(o.signalDefinition),{json:t.json,contract:o.signalDefinition})},qZ=async(e,t)=>{let{client:n}=As(t),r=f(await n.signalDefinitions.disable(e),"Couldn't disable signal definition",t.json);if(!t.json)z(`Signal definition "${r.signalDefinition.name}" disabled.`);R(Yu,xs(r.signalDefinition),{json:t.json,contract:r.signalDefinition})},MR=q("signal-definitions","Manage CEL signal definitions").withSubcommands({list:v("list","List signal definitions",async(e)=>{let{values:t}=S(e,Os);await FZ({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions(Ps).withExamples(["sazabi signal-definitions list --json # List signal definitions"]).build(),get:v("get","Get one signal definition by ID",async(e)=>{let{values:t,positionals:n}=S(e,Os,{allowPositionals:!0}),r=AS(n,t.json);if(!r)return;await BZ(r,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<signal-definition-id>").withOptions(Ps).withExamples(["sazabi signal-definitions get <signal-definition-id> --json # Get one signal definition"]).build(),create:v("create","Create a signal definition",async(e)=>{let{values:t,positionals:n}=S(e,{...Os,expression:{type:"string"},enabled:{type:"boolean"},disabled:{type:"boolean"}},{allowPositionals:!0}),r=MZ(n,t.json);if(!r)return;let o=(i)=>{if(t.json){h(i);return}g(i)};await GZ(r,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],expression:t.expression,enabled:t.enabled,disabled:t.disabled})}).withPositionalArgs("<name>").withOptions({...Ps,expression:{type:"string",description:"CEL expression evaluated against ingested logs"},enabled:{type:"boolean",description:"Create the signal definition enabled"},disabled:{type:"boolean",description:"Create the signal definition disabled"}}).withExamples([`sazabi signal-definitions create plain-tickets --expression 'service == "plain"' --json # Create a signal definition`]).build(),update:v("update","Update a signal definition",async(e)=>{let{values:t,positionals:n}=S(e,{...Os,name:{type:"string"},expression:{type:"string"},enable:{type:"boolean"},disable:{type:"boolean"}},{allowPositionals:!0}),r=AS(n,t.json);if(!r)return;let o=(i)=>{if(t.json){h(i);return}g(i)};await KZ(r,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],name:t.name,expression:t.expression,enable:t.enable,disable:t.disable})}).withPositionalArgs("<signal-definition-id>").withOptions({...Ps,name:{type:"string",description:"New signal definition name"},expression:{type:"string",description:"New CEL expression body"},enable:{type:"boolean",description:"Enable the signal definition"},disable:{type:"boolean",description:"Disable the signal definition"}}).withExamples([`sazabi signal-definitions update <signal-definition-id> --expression 'severity == "ERROR"' --json # Update signal definition CEL`]).build(),disable:v("disable","Disable a signal definition",async(e)=>{let{values:t,positionals:n}=S(e,Os,{allowPositionals:!0}),r=AS(n,t.json);if(!r)return;await qZ(r,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<signal-definition-id>").withOptions(Ps).withExamples(["sazabi signal-definitions disable <signal-definition-id> --json # Disable a signal definition"]).build()}).build();H();te();import*as kz from"node:os";import*as wz from"node:path";import*as Jn from"node:path";var Xu=["claude-code","codex","cursor","amp","opencode"],WZ={"claude-code":{user:(e)=>Jn.join(e,".claude","skills"),project:(e)=>Jn.join(e,".claude","skills")},codex:{user:(e)=>Jn.join(e,".agents","skills"),project:(e)=>Jn.join(e,".agents","skills")},amp:{user:(e)=>Jn.join(e,".config","agents","skills"),project:(e)=>Jn.join(e,".agents","skills")},opencode:{user:(e)=>Jn.join(e,".config","opencode","skills"),project:(e)=>Jn.join(e,".opencode","skills")}},VZ="Cursor does not support agent skills. Use Cursor Rules (.cursor/rules/*.mdc) instead. See https://cursor.com/docs/context/rules.",FR=(e)=>{if(e.agent==="cursor")return{kind:"unsupported",agent:"cursor",reason:VZ};let t=WZ[e.agent],n=e.scope==="user"?t.user(e.home):t.project(e.projectDir);return{kind:"supported",agent:e.agent,scope:e.scope,root:n}};import{dirname as eY,resolve as tY}from"node:path";import{fileURLToPath as nY}from"node:url";var BR="## Overview\n\nSend Claude Code session telemetry to Sazabi. Every session emits lifecycle events — prompts, tool calls, and model API requests with token counts and cost — as OTLP log records.\n\n## How it works\n\nClaude Code has a first-party OTLP exporter. Set a handful of environment variables in `~/.claude/settings.json` pointing the exporter at your Sazabi intake URL, and Claude Code sends telemetry over OTLP/HTTP on its own — no separate SDK or code changes required.\n\n## Streams\n\n- **Session events** — `claude_code.user_prompt`, `claude_code.tool_result`, `claude_code.api_request`, and related events, with attributes for `prompt`, `model`, `session.id`, `user.email`, token counts, and cost.\n\n## Limitations\n\n- Claude Code **metrics** are not ingested; only the logs exporter is supported.\n";var GR=`---
|
|
228
228
|
name: claude-code-log-source-setup
|
|
229
229
|
description: Export Claude Code session telemetry to a Sazabi project. Use when the user wants to "connect Claude Code", "set up Claude Code telemetry", "ingest Claude Code events", "send my coding agent telemetry to Sazabi", or after running \`sazabi log-sources skill --provider claude_code\`. Points Claude Code's built-in OTLP exporter at Sazabi's keyed intake host — no SDK or code changes required.
|