@sazabi/cli 1.0.0-dev.ga2c6079 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -8704,9 +8704,9 @@ Connect 1Password so Sazabi agents can work with your vaults and secrets through
|
|
|
8704
8704
|
- The 1Password CLI (\`op\`) sandbox preset, since no hosted MCP endpoint is available yet
|
|
8705
8705
|
`.trim()});import{dirname as L3A,resolve as S3A}from"node:path";import{fileURLToPath as l3A}from"node:url";var M3A,aBA,rBA,Y3A,bBA,$3A,k3A,G3A,NBA;var wf=D(()=>{TA();qa();M3A=S3A(L3A(l3A(import.meta.url)),"../../../skills"),aBA=["airbyte","atlassian","attio","autumn","aws","axiom","better-stack","braintrust","calendly","cekura","checkly","circleback","clay","clerk","cloudflare","composio","context-dev","custom","datadog","deepwiki","elastic-cloud","exa","gcp","google-drive","grafana","granola","happenstance","honeycomb","incident-io","intercom","langfuse","langsmith","linear","logfire","mercury","neon","notion","onepassword","paper","plug","posthog","plain","planetscale","pylon","railway","render","rentahuman","resend","respan","salesforce","secureframe","sentry","signoz","slack","stripe","supabase","superhuman","the-context-company","vercel","x"],rBA=I.enum(aBA),Y3A=I.object({readOnlyToolNames:I.array(I.string()).optional(),blockedToolNames:I.array(I.string()).optional(),defaultUnavailableReason:I.enum(xa).optional(),allowWriteTools:I.boolean().optional()}),bBA=I.object({registrationEndpoint:I.string().url(),tokenEndpointAuthMethod:I.enum(ma).optional(),includeScopesInRegistration:I.boolean().optional()}),$3A=I.object({providerConfigKey:I.string().min(1),callbackPathSegment:I.string().min(1),authorizationUrl:I.string().url().optional(),tokenUrl:I.string().url().optional(),resourceUrl:I.string().url().optional(),useServerUrlAsResource:I.boolean().optional(),omitScopeFromAuthorizationUrl:I.boolean().optional(),authorizationUrlParams:I.record(I.string(),I.string()).optional(),defaultAccessTokenTtlSeconds:I.number().int().positive().optional(),dynamicClientRegistration:bBA.optional()}),k3A=I.object({label:I.string().min(1),serverUrl:I.string().url(),authorizationUrl:I.string().url().optional(),tokenUrl:I.string().url().optional(),resourceUrl:I.string().url().optional(),dynamicClientRegistration:bBA.optional()}),G3A=I.object({id:I.string().min(1),title:I.string().min(1),description:I.string().optional(),body:I.string().min(1),fieldKeys:I.array(I.string().min(1)).optional(),imageKeys:I.array(I.string().min(1)).optional()}),NBA=I.object({id:I.string().min(1),label:I.string().min(1),iconKey:rBA,defaultServerUrl:I.string().url().nullable(),serverUrlPathSuffixMaxSegments:I.number().int().positive().optional(),serverUrlHostnameSuffixes:I.array(I.string().min(2)).optional(),transport:I.enum(Uk),authMode:I.enum(Fk),availability:I.enum(gh),oauth:$3A.optional(),regions:I.array(k3A).optional(),capabilityOverrides:Y3A.optional(),helpText:I.string().optional(),setupGroups:I.array(G3A).optional(),evidenceHints:I.array(I.string().min(1)).optional(),skill:I.string().min(1).optional(),setupSkill:I.string().min(1).optional(),scopesUserSelectable:I.boolean().optional()})});var V=(A)=>{return{...NBA.parse(A),...A.getAvailableScopes?{getAvailableScopes:A.getAvailableScopes}:{},...A.getUrlConfiguration?{getUrlConfiguration:A.getUrlConfiguration}:{},...A.validateCredentials?{validateCredentials:A.validateCredentials}:{},...A.normalizeHeaders?{normalizeHeaders:A.normalizeHeaders}:{}}};var eA=D(()=>{wf()});var uBA;var UBA=D(()=>{eA();uBA=V({id:"airbyte",label:"Airbyte",iconKey:"airbyte",defaultServerUrl:"https://mcp.airbyte.ai/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"airbyte",callbackPathSegment:"airbyte",authorizationUrl:"https://mcp.airbyte.ai/authorize",tokenUrl:"https://mcp.airbyte.ai/token",dynamicClientRegistration:{registrationEndpoint:"https://mcp.airbyte.ai/register",tokenEndpointAuthMethod:"client_secret_post"}},getAvailableScopes:async()=>[],scopesUserSelectable:!1,capabilityOverrides:{defaultUnavailableReason:"write_blocked"},evidenceHints:["Airbyte Agent Engine usage (mcp.airbyte.ai) or embedded agent connectors","AIRBYTE_* environment variables or Airbyte agent/connector client code","README/docs naming Airbyte for agent connectors to CRM, support, or analytics platforms"],helpText:"Read and write records on the third-party platforms (CRM, support desk, analytics, billing, databases) you have connected in your Airbyte Agent Engine workspace. Requires an Airbyte Agent Engine workspace with connectors already configured.",skill:"airbyte",setupSkill:"airbyte-setup"})});var FBA;var LBA=D(()=>{eA();FBA=V({id:"atlassian",label:"Atlassian",iconKey:"atlassian",defaultServerUrl:"https://mcp.atlassian.com/v1/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"atlassian",callbackPathSegment:"atlassian",authorizationUrl:"https://mcp.atlassian.com/v1/authorize",tokenUrl:"https://cf.mcp.atlassian.com/v1/token",dynamicClientRegistration:{registrationEndpoint:"https://cf.mcp.atlassian.com/v1/register",tokenEndpointAuthMethod:"none"}},scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["atlassian.com, Jira, Confluence, Jira Service Management, Compass, or Bitbucket links","Jira or Confluence project keys, issue keys, or workspace documentation","ATLASSIAN_* environment variables or scripts that call Atlassian APIs"],helpText:"Search and manage Jira, Confluence, Jira Service Management, Compass, and Bitbucket. During authorization, pick the Atlassian site you want to connect.",skill:"atlassian",setupSkill:"atlassian-setup"})});var SBA;var lBA=D(()=>{eA();SBA=V({id:"attio",label:"Attio",iconKey:"attio",defaultServerUrl:"https://mcp.attio.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"attio",callbackPathSegment:"attio",authorizationUrl:"https://app.attio.com/oidc/authorize",tokenUrl:"https://app.attio.com/oidc/token",dynamicClientRegistration:{registrationEndpoint:"https://app.attio.com/oauth/register",tokenEndpointAuthMethod:"none"}},scopesUserSelectable:!1,getAvailableScopes:async()=>[{value:"mcp",label:"MCP access",description:"Read and manage Attio CRM records, lists, tasks, notes, and meetings."},{value:"openid",required:!0},{value:"offline_access",required:!0}],getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["attio.com links, Attio workspace docs, or ATTIO_* environment variables","CRM account/contact workflows that reference Attio objects, lists, or tasks","README/docs naming Attio as the CRM or customer system of record"],helpText:"Search and manage Attio CRM records, lists, tasks, notes, and meetings. During authorization, pick the Attio workspace you want to connect.",skill:"attio",setupSkill:"attio-setup"})});var MBA;var YBA=D(()=>{Jt();eA();MBA=V({id:"autumn",label:"Autumn",iconKey:"autumn",defaultServerUrl:"https://mcp.useautumn.com/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["useautumn.com / autumn-js SDK usage, AUTUMN_SECRET_KEY (am_sk_) environment variables, or an api.useautumn.com base URL","Autumn billing/pricing calls such as attach, check, track, or entitlement gating in code","README/docs naming Autumn for pricing, plans, features, credits, or usage-based billing on top of Stripe"],helpText:"Manage Autumn billing and pricing — customers, plans, features, balances, usage, and subscriptions — using an Autumn secret key.",setupGroups:[{id:"api-key",title:"Create an Autumn secret key",description:"Copy the Autumn secret key Sazabi will send to Autumn's hosted MCP endpoint.",body:"In the [Autumn dashboard](https://app.useautumn.com), open **Developer > API Keys** and copy a secret key (`am_sk_...`). Use a sandbox key to explore and a production key for live billing data. Sazabi stores it securely and sends it as `Authorization: Bearer <key>` to Autumn's MCP endpoint.",fieldKeys:["apiKey"]}],validateCredentials:oBA,normalizeHeaders:iBA})});var p0,FGt,$BA;var s0=D(()=>{eA();p0=[{value:"us-east-1",label:"US East (N. Virginia) — us-east-1"},{value:"eu-central-1",label:"Europe (Frankfurt) — eu-central-1"}],FGt=new Set(p0.map((A)=>A.value)),$BA=V({id:"aws",label:"AWS",iconKey:"aws",defaultServerUrl:"https://aws-mcp.us-east-1.api.aws/mcp",transport:"streamable-http",authMode:"aws-sigv4",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["AWS SDK usage, aws-cli, or AWS_* environment variables in code or config","CloudFormation/CDK/Terraform AWS resources, ECS/Lambda/S3/CloudWatch usage","README/runbooks naming AWS as the cloud platform"],helpText:"Query the AWS-managed AWS MCP server (AWS documentation and AWS API operations) using AWS IAM credentials. Sazabi signs each request with SigV4, so no local proxy is required.",setupGroups:[{id:"iam-credentials",title:"Create scoped IAM credentials",description:"Provide IAM credentials whose permissions match exactly what the agent should be able to do.",body:"In the AWS Console, create an IAM user or role with only the permissions Sazabi should use (for example read-only access via `ReadOnlyAccess`, or a scoped custom policy), then generate an access key. Paste the **Access key ID** and **Secret access key** below. For temporary credentials from an assumed role, also paste the **Session token**. Prefer short-lived, least-privilege credentials.",fieldKeys:["accessKeyId","secretAccessKey","sessionToken"]},{id:"region",title:"Choose the AWS region",description:"The AWS MCP server is region-scoped; pick the region to target.",body:"Select the region where AWS hosts the AWS MCP endpoint. AWS currently offers the AWS MCP server in **US East (N. Virginia) — us-east-1** and **Europe (Frankfurt) — eu-central-1** only. Sazabi builds the `https://aws-mcp.<region>.api.aws/mcp` server URL from your choice and scopes SigV4 signing to it. This is the endpoint region, not the AWS region your API operations target.",fieldKeys:["region"]}]})});var kBA;var GBA=D(()=>{eA();kBA=V({id:"axiom",label:"Axiom",iconKey:"axiom",defaultServerUrl:"https://mcp.axiom.co/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"axiom",callbackPathSegment:"axiom",authorizationUrl:"https://mcp.axiom.co/authorize",tokenUrl:"https://mcp.axiom.co/token",dynamicClientRegistration:{registrationEndpoint:"https://mcp.axiom.co/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[],scopesUserSelectable:!1,getUrlConfiguration:async()=>({docsUrl:"https://axiom.co/docs/console/intelligence/mcp-server",instructions:"Copy the hosted MCP server URL below. If you belong to more than one Axiom organization, append ?org-id=<id> to target a specific organization.",defaultServerUrl:"https://mcp.axiom.co/mcp",optional:!0}),capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Axiom datasets, APL queries, AXIOM_* environment variables, or axiom CLI usage","Log drains or dashboards documented in Axiom","README/docs naming Axiom as a log or event analytics backend"],helpText:"Query Axiom datasets and logs with APL to investigate production events and incidents."})});var JBA;var TBA=D(()=>{eA();JBA=V({id:"better-stack",label:"Better Stack",iconKey:"better-stack",defaultServerUrl:"https://mcp.betterstack.com",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"better-stack",callbackPathSegment:"better-stack",authorizationUrl:"https://betterstack.com/oauth/authorize",tokenUrl:"https://betterstack.com/oauth/token",dynamicClientRegistration:{registrationEndpoint:"https://betterstack.com/oauth/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[{value:"read",label:"Read",description:"Read Better Stack incidents, monitors, log sources, and telemetry."},{value:"write",label:"Write",description:"Acknowledge, resolve, and manage Better Stack incidents."}],scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Better Stack / Better Uptime monitors, heartbeats, or status pages","BETTERSTACK_* or LOGTAIL_* environment variables, or Logtail/Better Stack log drains","README/docs naming Better Stack for uptime monitoring, incidents, or log management"],helpText:"Browse Better Stack incidents, monitors, and log sources, build telemetry queries to investigate production issues, and acknowledge, resolve, and manage incidents."})});var RBA;var PBA=D(()=>{Jt();eA();RBA=V({id:"braintrust",label:"Braintrust",iconKey:"braintrust",defaultServerUrl:"https://api.braintrust.dev/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["braintrust or autoevals packages, or BRAINTRUST_API_KEY environment variables","Braintrust eval/logging/tracing usage in code or CI (e.g. braintrust eval)","README/docs naming Braintrust for LLM evals, prompt/experiment tracking, or observability"],helpText:"Query Braintrust experiments, datasets, prompts, and logs using a Braintrust API key.",setupGroups:[{id:"api-key",title:"Create a Braintrust API key",description:"Generate the Braintrust API key the hosted MCP server will use.",body:"In Braintrust, go to **Settings > API keys** (https://www.braintrust.dev/app/settings/api-keys) and create an API key. Copy the generated key.",fieldKeys:["apiKey"]},{id:"data-plane",title:"Choose your Braintrust data plane",description:"Pick the region where your Braintrust data lives so Sazabi connects to the matching endpoint.",body:"Select **US** (`https://api.braintrust.dev/mcp`) or **EU** (`https://api-eu.braintrust.dev/mcp`) to match where your Braintrust data lives.",fieldKeys:["dataPlane"]}],validateCredentials:XIA,normalizeHeaders:VIA})});var fBA;var zBA=D(()=>{eA();fBA=V({id:"calendly",label:"Calendly",iconKey:"calendly",defaultServerUrl:"https://mcp.calendly.com",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"calendly",callbackPathSegment:"calendly",authorizationUrl:"https://calendly.com/oauth/authorize",tokenUrl:"https://calendly.com/oauth/token",dynamicClientRegistration:{registrationEndpoint:"https://calendly.com/oauth/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[],scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["calendly.com scheduling links or Calendly webhook handlers","CALENDLY_* environment variables or API integrations","README/docs naming Calendly for customer calls, interviews, or demos"],helpText:"Check availability, create scheduling links, and manage meetings in Calendly."})});var OBA;var vBA=D(()=>{Jt();eA();OBA=V({id:"cekura",label:"Cekura",iconKey:"cekura",defaultServerUrl:"https://api.cekura.ai/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",evidenceHints:["Cekura workflow tests, monitor configs, or CEKURA_* environment variables","Agent evaluation or production monitor docs naming Cekura","Synthetic user-flow tests for AI agents"],helpText:"Test, monitor, and evaluate AI agent workflows with Cekura.",setupGroups:[{id:"api-key",title:"Create an API key",description:"Create or copy the API key Sazabi will send to Cekura's hosted MCP endpoint.",body:"In the Cekura dashboard, open **Settings > API Keys** and create or copy a project-scoped [API key](https://dashboard.cekura.ai/settings/org/api-key), then paste it below.",fieldKeys:["apiKey"]}],validateCredentials:yBA})});var ZBA;var WBA=D(()=>{eA();ZBA=V({id:"checkly",label:"Checkly MCP",iconKey:"checkly",defaultServerUrl:"https://api.checklyhq.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"disabled",oauth:{providerConfigKey:"checkly",callbackPathSegment:"checkly"},getAvailableScopes:async()=>[{value:"checkly:account:read"},{value:"checkly:account:invite"},{value:"checkly:checks:read"},{value:"checkly:checks:run"},{value:"checkly:incidents:read"},{value:"checkly:incidents:write"},{value:"checkly:environment-variables:read"},{value:"checkly:environment-variables:write"},{value:"checkly:status-pages:read"},{value:"checkly:rca:read"},{value:"checkly:rca:run"},{value:"checkly:test-sessions:read"},{value:"checkly:assets:read"}],scopesUserSelectable:!1,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["checkly.config.ts/js, __checks__ directories, @checkly/cli, or CHECKLY_* environment variables","README/docs naming Checkly for synthetic monitoring, API checks, or browser checks","Runbooks that inspect Checkly check results, test sessions, RCA, status pages, or incidents"],helpText:"Query Checkly synthetic monitoring (checks, check results, test sessions, RCA, status pages, and incidents) over Checkly's official OAuth MCP server. Disabled until Sazabi has a Checkly-approved OAuth client, because Checkly rejects Dynamic Client Registration."})});var VBA;var XBA=D(()=>{eA();VBA=V({id:"circleback",label:"Circleback",iconKey:"circleback",defaultServerUrl:"https://circleback.ai/api/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"circleback",callbackPathSegment:"circleback",authorizationUrl:"https://circleback.ai/api/oauth/authorize",tokenUrl:"https://circleback.ai/api/oauth/access-token",dynamicClientRegistration:{registrationEndpoint:"https://circleback.ai/api/oauth/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[],scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["circleback.ai meeting links, Circleback notes exports, or CIRCLEBACK_* environment variables","Incident, customer-call, or product-feedback docs naming Circleback","Operational runbooks that refer to meeting notes or transcripts in Circleback"],helpText:"Search your Circleback meeting notes, transcripts, and action items."})});var HBA;var KBA=D(()=>{eA();HBA=V({id:"clay",label:"Clay",iconKey:"clay",defaultServerUrl:"https://mcp.clay.earth/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"clay",callbackPathSegment:"clay",authorizationUrl:"https://mcp.clay.earth/authorize",tokenUrl:"https://mcp.clay.earth/token",dynamicClientRegistration:{registrationEndpoint:"https://mcp.clay.earth/register",tokenEndpointAuthMethod:"client_secret_post"}},getAvailableScopes:async()=>[{value:"openid",required:!0},{value:"read",label:"Read access",description:"Read Clay contacts, interactions, notes, and workspace workflows."},{value:"write",label:"Write access",description:"Create and update Clay records and workspace workflows."}],getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Clay workflow URLs, clay.earth links, or CLAY_* environment variables","Outbound enrichment, lead routing, or contact workflow docs naming Clay","Code or scripts that sync contacts, notes, or workspace workflows with Clay"],helpText:"Search Clay contacts, interactions, notes, and workspace workflows, and create or update records and workflows."})});var jBA;var _BA=D(()=>{eA();jBA=V({id:"clerk",label:"Clerk",iconKey:"clerk",defaultServerUrl:"https://mcp.clerk.com/mcp",transport:"streamable-http",authMode:"none",availability:"enabled",capabilityOverrides:{readOnlyToolNames:["list_clerk_sdk_snippets","clerk_sdk_snippet"]},evidenceHints:["@clerk/* SDK imports, CLERK_SECRET_KEY / CLERK_PUBLISHABLE_KEY environment variables, or clerk.com URLs","Authentication, session, or organization/user management logic built on Clerk","README/docs naming Clerk for auth, sign-in flows, or user management"],helpText:"Search Clerk's public documentation and SDK implementation snippets via Clerk's hosted MCP server."})});var mBA;var xBA=D(()=>{eA();mBA=V({id:"cloudflare",label:"Cloudflare",iconKey:"cloudflare",defaultServerUrl:"https://mcp.cloudflare.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"cloudflare",callbackPathSegment:"cloudflare",authorizationUrl:"https://mcp.cloudflare.com/authorize",tokenUrl:"https://mcp.cloudflare.com/token",dynamicClientRegistration:{registrationEndpoint:"https://mcp.cloudflare.com/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[],scopesUserSelectable:!1,regions:[{label:"Cloudflare API (all products, account-scoped)",serverUrl:"https://mcp.cloudflare.com/mcp"},{label:"Observability (Workers logs & analytics)",serverUrl:"https://observability.mcp.cloudflare.com/mcp",authorizationUrl:"https://observability.mcp.cloudflare.com/oauth/authorize",tokenUrl:"https://observability.mcp.cloudflare.com/token",dynamicClientRegistration:{registrationEndpoint:"https://observability.mcp.cloudflare.com/register",tokenEndpointAuthMethod:"none"}},{label:"Workers Bindings (D1, R2, KV, Workers)",serverUrl:"https://bindings.mcp.cloudflare.com/mcp",authorizationUrl:"https://bindings.mcp.cloudflare.com/oauth/authorize",tokenUrl:"https://bindings.mcp.cloudflare.com/token",dynamicClientRegistration:{registrationEndpoint:"https://bindings.mcp.cloudflare.com/register",tokenEndpointAuthMethod:"none"}},{label:"Workers Builds (CI/CD builds)",serverUrl:"https://builds.mcp.cloudflare.com/mcp",authorizationUrl:"https://builds.mcp.cloudflare.com/oauth/authorize",tokenUrl:"https://builds.mcp.cloudflare.com/token",dynamicClientRegistration:{registrationEndpoint:"https://builds.mcp.cloudflare.com/register",tokenEndpointAuthMethod:"none"}},{label:"Radar (Internet traffic insights)",serverUrl:"https://radar.mcp.cloudflare.com/mcp",authorizationUrl:"https://radar.mcp.cloudflare.com/oauth/authorize",tokenUrl:"https://radar.mcp.cloudflare.com/token",dynamicClientRegistration:{registrationEndpoint:"https://radar.mcp.cloudflare.com/register",tokenEndpointAuthMethod:"none"}}],capabilityOverrides:{allowWriteTools:!0},evidenceHints:["wrangler.toml / wrangler.jsonc, @cloudflare/* packages, or CLOUDFLARE_* environment variables","Cloudflare Workers, Pages, R2, D1, KV, or Durable Objects usage in code or config","README/runbooks naming Cloudflare as the CDN, edge, or Workers platform"],helpText:"By default, use Cloudflare's unified all-products API server (mcp.cloudflare.com), scoped by your account's permissions. Optionally pick a per-product server for observability logs and analytics, bindings (D1, R2, KV), builds, or Radar insights."})});var qBA;var dBA=D(()=>{Jt();eA();qBA=V({id:"cloudflare-api-token",label:"Cloudflare (API token)",iconKey:"cloudflare",defaultServerUrl:"https://mcp.cloudflare.com/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["wrangler.toml / wrangler.jsonc, @cloudflare/* packages, or CLOUDFLARE_* environment variables","Cloudflare Workers, Pages, R2, D1, KV, or Durable Objects usage in code or config","README/runbooks naming Cloudflare as the CDN, edge, or Workers platform"],helpText:"Query the Cloudflare API MCP server (Workers, DNS, zones, and more) using a Cloudflare API token instead of OAuth.",setupGroups:[{id:"api-token",title:"Create a Cloudflare API token",description:"Mint an API token scoped to exactly the products and permissions Sazabi should access.",body:"In the Cloudflare dashboard, go to **My Profile > API Tokens > Create Token**, then **Create Custom Token**. Under **Permissions**, add read access for the products you want the agent to use — for example **Account > Workers Observability > Read**, **Zone > DNS > Read**, and **Account > Account Settings > Read** — then copy the generated `cfut_...` token. Tokens with **Client IP Address Filtering** enabled are not supported by the hosted MCP server.",fieldKeys:["apiToken"]}],validateCredentials:zIA,normalizeHeaders:fIA})});var pBA;var sBA=D(()=>{Jt();eA();pBA=V({id:"composio",label:"Composio",iconKey:"composio",defaultServerUrl:"https://connect.composio.dev/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Composio MCP, COMPOSIO_API_KEY, or Composio SDK usage","connect.composio.dev/mcp in MCP client configuration","README/docs naming Composio integrations, toolkits, or connected apps"],helpText:"Use tools from the Composio toolkits you have connected, through Composio's hosted Connect MCP server with a Composio API key.",setupGroups:[{id:"connect-toolkits",title:"Connect the toolkits you want to use",description:"Composio's MCP server only exposes tools for the apps you have connected in Composio.",body:"In the [Composio dashboard](https://dashboard.composio.dev), connect the apps (toolkits) you want the agent to use. Composio can also prompt to connect apps on demand at runtime, but connecting them first makes those tools available right away."},{id:"api-key",title:"Create an API key",description:"Create or copy the Composio API key Sazabi will send to Composio's hosted MCP endpoint.",body:"In the [Composio dashboard](https://dashboard.composio.dev), open **Settings > Project Settings** and copy your project API key from the **API Keys** section (or use the AI Clients page). Paste it below. Sazabi stores it securely and sends it as the `x-consumer-api-key` header to Composio's Connect MCP endpoint.",fieldKeys:["apiKey"]}],validateCredentials:sIA,normalizeHeaders:pIA})});var AhA;var thA=D(()=>{Jt();eA();AhA=V({id:"context-dev",label:"Context.dev",iconKey:"context-dev",defaultServerUrl:"https://context-dev.stlmcp.com",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Context.dev SDK usage (context.dev on npm/PyPI/RubyGems), CONTEXT_DEV_API_KEY environment variables, or ctxt_secret_ API keys","context.dev-mcp usage or a context-dev.stlmcp.com server URL in MCP client config","README/docs naming Context.dev for brand intelligence, web scraping/crawling, or website change monitors"],helpText:"Resolve brand data, scrape and crawl websites into LLM-ready Markdown, extract structured data, and manage website-change monitors with Context.dev's hosted MCP server using your Context.dev API key.",setupGroups:[{id:"api-key",title:"Create an API key",description:"Create or copy the Context.dev API key Sazabi will send to Context.dev's hosted MCP endpoint.",body:"Create or copy an API key (`ctxt_secret_...`) from your [Context.dev dashboard](https://context.dev), then paste it below. Sazabi stores it securely and sends it as the `x-context-dev-api-key` header to Context.dev's MCP endpoint.",fieldKeys:["apiKey"]}],validateCredentials:nBA,normalizeHeaders:gBA,skill:"context-dev",setupSkill:"context-dev-setup"})});var ghA;var nhA=D(()=>{Jt();eA();ghA=V({id:"datadog",label:"Datadog",iconKey:"datadog",defaultServerUrl:"https://mcp.datadoghq.com/api/unstable/mcp-server/mcp?toolsets=core",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Datadog config, DD_* environment variables, or @datadog packages","datadog-agent, dd-trace, monitors, dashboards, or incident docs","README/docs naming Datadog for logs, metrics, traces, APM, or incidents"],helpText:"Browse Datadog metrics, logs, traces, and incidents using your Datadog site URL, API key, and Application Key.",setupGroups:[{id:"site",title:"Find your Datadog site",description:"Use the Datadog site URL for the region where your account lives.",body:"Copy the Datadog site URL from the top of your browser, such as `https://app.datadoghq.com` or `https://us3.datadoghq.com`. Sazabi uses this to build the matching hosted MCP endpoint.",fieldKeys:["siteUrl"]},{id:"keys",title:"Create API credentials",description:"Create or copy the two Datadog keys Sazabi needs for hosted MCP.",imageKeys:["mcp.datadog.api-keys-settings","mcp.datadog.application-keys-settings"],body:"In Datadog, go to **Organization Settings > Access > API Keys** to create or copy your API key. Then go to **Organization Settings > Access > Application Keys** to create or copy your Application Key. Note: an Application Key inherits the permissions of the user who creates it, so create it as a least-privilege user or scope the key down to only what the agent needs.",fieldKeys:["apiKey","applicationKey"]}],validateCredentials:PIA,normalizeHeaders:TIA})});var ihA;var QhA=D(()=>{eA();ihA=V({id:"deepwiki",label:"DeepWiki",iconKey:"deepwiki",defaultServerUrl:"https://mcp.deepwiki.com/mcp",transport:"streamable-http",authMode:"none",availability:"enabled",capabilityOverrides:{readOnlyToolNames:["read_wiki_structure","read_wiki_contents","ask_question"]},evidenceHints:["Questions about how a public GitHub repository or open-source dependency works","deepwiki.com URLs or references to DeepWiki-generated documentation","Investigations needing up-to-date docs/architecture for a third-party OSS project"],helpText:"Query public GitHub repository documentation and ask questions about open-source code via DeepWiki's hosted MCP server."})});var ohA;var IhA=D(()=>{Jt();eA();ohA=V({id:"elastic-cloud",label:"Elastic Cloud",iconKey:"elastic-cloud",defaultServerUrl:null,serverUrlHostnameSuffixes:[".elastic.cloud",".cloud.es.io",".elastic-cloud.com"],transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Elasticsearch, Kibana, Elastic Agent, Beats, or Logstash config","ELASTIC_* environment variables or elasticsearch client packages","README/docs naming Elastic Cloud, Elasticsearch, or Kibana"],helpText:"Search Elasticsearch indices and query Elastic Agent Builder tools using your Kibana MCP endpoint and an Elastic API key.",setupGroups:[{id:"deployment",title:"Open Kibana",description:"Find the Kibana URL for the Elastic deployment you want to connect.",body:"Go to [Elastic Cloud deployments](https://cloud.elastic.co/deployments), open the deployment you want to connect, then open Kibana and copy the Kibana base URL from the browser. If your Kibana URL contains `/s/<space>/`, keep that space value for the connect step.",fieldKeys:["kibanaUrl","kibanaSpace"]},{id:"api-key",title:"Create an API key",description:"Create the Elastic API key that the hosted MCP server will use.",body:"In Kibana, go to **Stack Management > API keys** and choose **Create API key**. Restrict its privileges to the Agent Builder MCP server: the `feature_agentBuilder.read` and `feature_actions.read` Kibana privileges, plus read access to the indices your tools query. Copy the generated key.",fieldKeys:["apiKey"]}],validateCredentials:RIA,normalizeHeaders:JIA})});var BhA;var hhA=D(()=>{Jt();eA();BhA=V({id:"exa",label:"Exa",iconKey:"exa",defaultServerUrl:"https://mcp.exa.ai/mcp?tools=web_search_exa,web_fetch_exa,web_search_advanced_exa,agent_tools",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Exa search, EXA_API_KEY environment variables, or the exa-js / exa-py SDK","exa-mcp-server usage or a mcp.exa.ai server URL in MCP client config","README/docs naming Exa for web search, crawling, or research"],helpText:"Search the web, research companies, crawl pages, and run deep research with Exa's hosted MCP server using your Exa API key.",setupGroups:[{id:"api-key",title:"Create an API key",description:"Create or copy the Exa API key Sazabi will send to Exa's hosted MCP endpoint.",body:"Create or copy an API key from the [Exa dashboard](https://dashboard.exa.ai/api-keys), then paste it below. Sazabi stores it securely and sends it as the `x-api-key` header to Exa's MCP endpoint.",fieldKeys:["apiKey"]}],validateCredentials:dIA,normalizeHeaders:qIA,skill:"exa",setupSkill:"exa-setup"})});var ehA;var ChA=D(()=>{Jt();eA();ehA=V({id:"gcp",label:"Google Cloud (GCP)",iconKey:"gcp",defaultServerUrl:"https://logging.googleapis.com/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["GOOGLE_APPLICATION_CREDENTIALS, GCLOUD_PROJECT, or GOOGLE_CLOUD_PROJECT environment variables","gcloud config, app.yaml, cloudbuild.yaml, or @google-cloud/* packages","README/docs naming Google Cloud, GCP, Cloud Logging, Cloud Monitoring, BigQuery, Cloud Run, or GKE"],helpText:"Query Google Cloud (Cloud Logging, Monitoring, BigQuery, and more) using a Google OAuth 2.0 Bearer access token.",setupGroups:[{id:"server-url",title:"Choose the Google Cloud MCP endpoint",description:"Google exposes a separate remote MCP server per product at https://SERVICE.googleapis.com/mcp.",body:"Sazabi defaults to Cloud Logging (`https://logging.googleapis.com/mcp`). To use a different product, replace the server URL with its endpoint, such as `https://monitoring.googleapis.com/mcp` (Cloud Monitoring) or `https://bigquery.googleapis.com/mcp` (BigQuery). See the [supported products list](https://docs.cloud.google.com/mcp/supported-products)."},{id:"access-token",title:"Create a Google OAuth 2.0 access token",description:"Generate a Google access token scoped by IAM to the resources Sazabi should read.",body:"The hosted servers authenticate with a Google OAuth 2.0 Bearer access token. For a non-interactive token, install the [gcloud CLI](https://docs.cloud.google.com/mcp/authenticate-mcp), configure Application Default Credentials (a user login, service-account key, or impersonation), then run `gcloud auth application-default print-access-token` and copy the token. Paste the raw token into Sazabi — Sazabi adds the `Bearer ` prefix and sends it in the `Authorization` header. Google access tokens are short-lived, so refresh the token when it expires.",fieldKeys:["accessToken"]}],validateCredentials:EBA,normalizeHeaders:cBA})});var chA;var EhA=D(()=>{eA();chA=V({id:"google-drive",label:"Google Drive",iconKey:"google-drive",defaultServerUrl:"https://drivemcp.googleapis.com/mcp/v1",transport:"streamable-http",authMode:"oauth",availability:"disabled",oauth:{providerConfigKey:"google-drive",callbackPathSegment:"google-drive",authorizationUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",authorizationUrlParams:{access_type:"offline",prompt:"consent"}},scopesUserSelectable:!1,getAvailableScopes:async()=>[{value:"https://www.googleapis.com/auth/drive.readonly",label:"Drive read",description:"Read files and metadata in the user's Google Drive through the hosted MCP server."}],setupGroups:[{id:"google-cloud-oauth-client",title:"Create an OAuth client in Google Cloud",description:"The Google Drive MCP server does not support automatic client registration. An admin must create an OAuth client in a Google Cloud project and provide its credentials to Sazabi.",body:["1. In the Google Cloud console, open **APIs & Services → OAuth consent screen** and configure the consent screen with the Drive scopes.","2. Under **APIs & Services → Credentials**, create an **OAuth client ID** of type **Web application**.","3. Add the Sazabi Google Drive MCP callback URL shown on this page as an **Authorized redirect URI**.","4. Enable both the **Google Drive API** and the **Google Drive MCP API** (`drivemcp.googleapis.com`) for the project. Both are required for the hosted MCP server to be reachable.","5. Provide the generated **Client ID** and **Client Secret** to your Sazabi deployment configuration."].join(`
|
|
8706
8706
|
`)}],evidenceHints:["drive.google.com / docs.google.com links, or Google Drive file IDs in runbooks","googleapis / google-auth-library packages, or GOOGLE_* / GDRIVE_* environment variables","README/runbooks naming Google Drive as a document or asset store"],helpText:"Search and read files and metadata in a Google Drive through Google's hosted MCP server. Coming soon — requires a Sazabi-provisioned Google OAuth client and isn't self-serve connectable yet."})});var yhA;var DhA=D(()=>{eA();yhA=V({id:"grafana",label:"Grafana Cloud",iconKey:"grafana",defaultServerUrl:"https://mcp.grafana.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"grafana",callbackPathSegment:"grafana",authorizationUrl:"https://mcp.grafana.com/mcp/oauth/authorize",tokenUrl:"https://mcp.grafana.com/mcp/oauth/token",dynamicClientRegistration:{registrationEndpoint:"https://mcp.grafana.com/mcp/oauth/register",tokenEndpointAuthMethod:"none"}},scopesUserSelectable:!1,getAvailableScopes:async()=>[{value:"grafana:read",label:"Read",description:"Read Grafana dashboards, panels, metrics, logs, traces, alerts, and incidents."},{value:"grafana:write",label:"Write",description:"Create and modify Grafana resources. Write tools require explicit approval per your organization's tool policy."}],getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["grafana.net / grafana.com links, Grafana dashboards, or GRAFANA_* environment variables","Prometheus, Loki, Tempo, or Mimir data sources wired into Grafana","README/runbooks naming Grafana for dashboards, metrics, logs, traces, or alerts"],helpText:"Browse Grafana dashboards, metrics, logs, traces, and alerts across your Grafana Cloud stack."})});var whA;var ahA=D(()=>{eA();whA=V({id:"granola",label:"Granola",iconKey:"granola",defaultServerUrl:"https://mcp.granola.ai/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"granola",callbackPathSegment:"granola",authorizationUrl:"https://mcp-auth.granola.ai/oauth2/authorize",tokenUrl:"https://mcp-auth.granola.ai/oauth2/token",dynamicClientRegistration:{registrationEndpoint:"https://mcp-auth.granola.ai/oauth2/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[{value:"offline_access",required:!0}],scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["granola.ai meeting links, Granola notes exports, or GRANOLA_* environment variables","Incident, customer-call, or product-feedback docs naming Granola","Operational runbooks that refer to meeting notes or transcripts in Granola"],helpText:"Search and browse Granola meeting notes, transcripts, and folders."})});var rhA;var bhA=D(()=>{eA();rhA=V({id:"happenstance",label:"Happenstance",iconKey:"happenstance",defaultServerUrl:"https://happenstance.ai/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"happenstance",callbackPathSegment:"happenstance",authorizationUrl:"https://happenstance.ai/oauth/authorize",tokenUrl:"https://clerk.happenstance.ai/oauth/token",dynamicClientRegistration:{registrationEndpoint:"https://clerk.happenstance.ai/oauth/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[{value:"profile",label:"Profile",description:"Read your Happenstance profile."},{value:"email",label:"Email",description:"Read the email associated with your Happenstance account."},{value:"offline_access",label:"Offline access",description:"Keep the connection alive by refreshing access without re-authentication."}],scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["happenstance.ai links or references to a Happenstance network/graph","HAPPENSTANCE_* environment variables or scripts calling Happenstance APIs","Docs naming Happenstance as the people/relationship search tool"],helpText:"Search your Happenstance network to find and get introduced to people."})});var NhA;var uhA=D(()=>{eA();NhA=V({id:"honeycomb",label:"Honeycomb",iconKey:"honeycomb",defaultServerUrl:"https://mcp.honeycomb.io/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"honeycomb",callbackPathSegment:"honeycomb",authorizationUrl:"https://ui.honeycomb.io/oauth/authorize",tokenUrl:"https://ui.honeycomb.io/oauth/token",dynamicClientRegistration:{registrationEndpoint:"https://ui.honeycomb.io/oauth/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[{value:"mcp:read",label:"Read",description:"Query Honeycomb environments, datasets, columns, boards, triggers, SLOs, and run queries."},{value:"mcp:write",label:"Write",description:"Create and update Honeycomb boards, triggers, and other resources."}],scopesUserSelectable:!1,regions:[{label:"United States (US)",serverUrl:"https://mcp.honeycomb.io/mcp"},{label:"Europe (EU)",serverUrl:"https://mcp.eu1.honeycomb.io/mcp",authorizationUrl:"https://ui.eu1.honeycomb.io/oauth/authorize",tokenUrl:"https://ui.eu1.honeycomb.io/oauth/token",dynamicClientRegistration:{registrationEndpoint:"https://ui.eu1.honeycomb.io/oauth/register",tokenEndpointAuthMethod:"none"}}],capabilityOverrides:{allowWriteTools:!0},evidenceHints:["honeycomb.io URLs, HONEYCOMB_API_KEY / HONEYCOMB_DATASET environment variables, or honeycomb:// dataset URIs","libhoney, @honeycombio packages, or OpenTelemetry exporters pointed at api.honeycomb.io / api.eu1.honeycomb.io","README/runbooks naming Honeycomb as the observability or tracing provider"],helpText:"Query Honeycomb environments, datasets, columns, boards, and triggers, run queries, and create or update boards and triggers. Choose the US or EU region when connecting."})});var UhA;var FhA=D(()=>{eA();UhA=V({id:"incident-io",label:"incident.io",iconKey:"incident-io",defaultServerUrl:"https://mcp.incident.io/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"incident-io",callbackPathSegment:"incident-io",authorizationUrl:"https://app.incident.io/auth/plugin/authorize",tokenUrl:"https://app.incident.io/auth/plugin/token",dynamicClientRegistration:{registrationEndpoint:"https://mcp.incident.io/mcp/oauth/register",tokenEndpointAuthMethod:"none"}},scopesUserSelectable:!1,getAvailableScopes:async()=>[],getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["incident.io alert-source URLs, escalation docs, or incident IDs","INCIDENT_IO_* environment variables or webhooks into incident.io","README/runbooks naming incident.io for incidents, alerts, or on-call"],helpText:"Browse incidents, alerts, and on-call.",skill:"incident-io",setupSkill:"incident-io-setup"})});var LhA;var ShA=D(()=>{Jt();eA();LhA=V({id:"intercom",label:"Intercom",iconKey:"intercom",defaultServerUrl:"https://mcp.intercom.com/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Intercom config, INTERCOM_* environment variables, or intercom-client packages","Support inbox, conversations, help center, or customer messaging docs naming Intercom","README/docs naming Intercom for support threads or customer conversations"],helpText:"Read Intercom support conversations, contacts, and help center content using an Intercom API access token. US-hosted Intercom workspaces only.",setupGroups:[{id:"developer-app",title:"Open Intercom developer settings",description:"Use an Intercom app with an access token for the workspace you want to connect.",body:"In Intercom, go to **Settings > Integrations > Developer Hub**, open (or create) an app for your workspace, and confirm it has the permissions you want agents to use. The hosted MCP server lives at `https://mcp.intercom.com/mcp` and currently supports US-hosted Intercom workspaces only."},{id:"access-token",title:"Copy your access token",description:"Copy the Intercom API access token the hosted MCP server will use.",body:"From your Intercom app's **Authentication** section, copy the access token. Paste the raw token into Sazabi — Sazabi adds the `Bearer ` prefix and sends it in the `Authorization` header.",fieldKeys:["accessToken"]}],validateCredentials:KIA,normalizeHeaders:HIA})});var lhA;var MhA=D(()=>{Jt();eA();lhA=V({id:"langfuse",label:"Langfuse",iconKey:"langfuse",defaultServerUrl:"https://us.cloud.langfuse.com/api/public/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",regions:[{label:"United States (US)",serverUrl:"https://us.cloud.langfuse.com/api/public/mcp"},{label:"Europe (EU)",serverUrl:"https://cloud.langfuse.com/api/public/mcp"},{label:"Asia Pacific (JP)",serverUrl:"https://jp.cloud.langfuse.com/api/public/mcp"}],capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Langfuse SDK usage (langfuse, langfuse-langchain) or @langfuse packages","LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY / LANGFUSE_HOST environment variables","README/docs naming Langfuse as the LLM tracing, evaluation, or observability provider"],helpText:"Query Langfuse traces, observations, metrics, scores, comments, and prompts using project API keys.",setupGroups:[{id:"region",title:"Pick your Langfuse Cloud region",description:"Select the Langfuse Cloud region that hosts your project (or use the custom connector for a self-hosted deployment).",body:"Langfuse Cloud is region-scoped: US (`https://us.cloud.langfuse.com`), EU (`https://cloud.langfuse.com`), or JP (`https://jp.cloud.langfuse.com`). Choose the region matching your Langfuse account; the hosted MCP server lives at `/api/public/mcp` on that host."},{id:"api-keys",title:"Create project API keys",description:"Generate the Langfuse project API key pair the hosted MCP server will use.",body:"In Langfuse, open **Project settings → API keys** and create a new key pair. Copy the Public key (`pk-lf-...`) and Secret key (`sk-lf-...`). Sazabi combines them into an HTTP Basic `Authorization` header (`Basic base64(publicKey:secretKey)`) and sends it to the MCP server. Paste the combined `Authorization` value into Sazabi.",fieldKeys:["authorization"]}],validateCredentials:IBA,normalizeHeaders:QBA})});var YhA;var $hA=D(()=>{eA();YhA=V({id:"langsmith",label:"LangSmith",iconKey:"langsmith",defaultServerUrl:"https://api.smith.langchain.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"langsmith",callbackPathSegment:"langsmith",authorizationUrl:"https://api.smith.langchain.com/oauth/authorize",tokenUrl:"https://api.smith.langchain.com/oauth/token",resourceUrl:"https://api.smith.langchain.com/mcp",dynamicClientRegistration:{registrationEndpoint:"https://api.smith.langchain.com/oauth/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[],scopesUserSelectable:!1,regions:[{label:"GCP United States (US)",serverUrl:"https://api.smith.langchain.com/mcp"},{label:"GCP Europe (EU)",serverUrl:"https://eu.api.smith.langchain.com/mcp",authorizationUrl:"https://eu.api.smith.langchain.com/oauth/authorize",tokenUrl:"https://eu.api.smith.langchain.com/oauth/token",resourceUrl:"https://eu.api.smith.langchain.com/mcp",dynamicClientRegistration:{registrationEndpoint:"https://eu.api.smith.langchain.com/oauth/register",tokenEndpointAuthMethod:"none"}},{label:"GCP Asia Pacific (APAC)",serverUrl:"https://apac.api.smith.langchain.com/mcp",authorizationUrl:"https://apac.api.smith.langchain.com/oauth/authorize",tokenUrl:"https://apac.api.smith.langchain.com/oauth/token",resourceUrl:"https://apac.api.smith.langchain.com/mcp",dynamicClientRegistration:{registrationEndpoint:"https://apac.api.smith.langchain.com/oauth/register",tokenEndpointAuthMethod:"none"}},{label:"AWS United States (US)",serverUrl:"https://aws.api.smith.langchain.com/mcp",authorizationUrl:"https://aws.api.smith.langchain.com/oauth/authorize",tokenUrl:"https://aws.api.smith.langchain.com/oauth/token",resourceUrl:"https://aws.api.smith.langchain.com/mcp",dynamicClientRegistration:{registrationEndpoint:"https://aws.api.smith.langchain.com/oauth/register",tokenEndpointAuthMethod:"none"}}],getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["LANGSMITH_* or LANGCHAIN_* environment variables, or langsmith SDK usage","LangSmith tracing projects, runs, datasets, or evaluations","README/docs naming LangSmith for LLM tracing, evals, or observability"],helpText:"Query LangSmith tracing projects, runs, datasets, and evaluations to investigate LLM application behavior. Choose the region where your LangSmith organization lives when connecting."})});var khA;var GhA=D(()=>{eA();khA=V({id:"linear",label:"Linear",iconKey:"linear",defaultServerUrl:"https://mcp.linear.app/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"linear",callbackPathSegment:"linear",authorizationUrl:"https://mcp.linear.app/authorize",tokenUrl:"https://mcp.linear.app/token",dynamicClientRegistration:{registrationEndpoint:"https://mcp.linear.app/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[{value:"read",label:"Read",description:"Read Linear issues, projects, teams, comments, and related data."},{value:"write",label:"Write",description:"Create and update Linear issues, comments, and project data."}],scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},skill:"linear",setupSkill:"linear-setup",evidenceHints:["linear.app URLs, Linear issue keys, or team/project IDs in docs","LINEAR_* environment variables or scripts that call Linear APIs","README/runbooks naming Linear as the issue tracker or planning system"],helpText:"Browse and search Linear issues and projects, and create or update issues, comments, and project data."})});var JhA;var ThA=D(()=>{eA();JhA=V({id:"logfire",label:"Pydantic Logfire",iconKey:"logfire",defaultServerUrl:"https://logfire-us.pydantic.dev/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"logfire",callbackPathSegment:"logfire",authorizationUrl:"https://logfire-us.pydantic.dev/api/oauth/authorize",tokenUrl:"https://logfire-us.pydantic.dev/api/oauth/token",dynamicClientRegistration:{registrationEndpoint:"https://logfire-us.pydantic.dev/api/oauth/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[{value:"openid",required:!0},{value:"organization:read_channel"},{value:"project:read"},{value:"project:read_alert"},{value:"project:read_dashboard"},{value:"project:read_variables"}],scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Pydantic Logfire config, LOGFIRE_* environment variables, or logfire SDK packages","Python/Pydantic observability docs naming Logfire","Alerts, dashboards, or traces hosted in Logfire"],helpText:"Query Pydantic Logfire traces, metrics, and exceptions, and browse projects, alerts, and dashboards. Hosted on Logfire's US region (logfire-us.pydantic.dev)."})});var RhA;var PhA=D(()=>{eA();RhA=V({id:"mercury",label:"Mercury",iconKey:"mercury",defaultServerUrl:"https://mcp.mercury.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"mercury",callbackPathSegment:"mercury",authorizationUrl:"https://mcp.mercury.com/authorize",tokenUrl:"https://mcp.mercury.com/token",resourceUrl:"https://mcp.mercury.com/mcp",omitScopeFromAuthorizationUrl:!0,dynamicClientRegistration:{registrationEndpoint:"https://mcp.mercury.com/register",tokenEndpointAuthMethod:"client_secret_basic",includeScopesInRegistration:!0}},getAvailableScopes:async()=>[{value:"read",label:"Read access",description:"Read Mercury accounts, cards, recipients, transactions, treasury, and organization data."},{value:"offline_access",required:!0}],scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!1},skill:"mercury",setupSkill:"mercury-setup",evidenceHints:["Mercury dashboard links, mercury.com references, or Mercury API usage","MERCURY_* environment variables or docs mentioning Mercury banking","Treasury, card, account, recipient, or transaction workflows backed by Mercury"],helpText:"Search Mercury banking data including accounts, cards, recipients, transactions, treasury, and organization records. Read-only: this connection cannot move money or change your Mercury account."})});var fhA;var zhA=D(()=>{eA();fhA=V({id:"neon",label:"Neon",iconKey:"neon",defaultServerUrl:"https://mcp.neon.tech/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"neon",callbackPathSegment:"neon",authorizationUrl:"https://mcp.neon.tech/api/authorize",tokenUrl:"https://mcp.neon.tech/api/token",dynamicClientRegistration:{registrationEndpoint:"https://mcp.neon.tech/api/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[{value:"read",label:"Read",description:"Read Neon projects, branches, databases, and run queries."},{value:"write",label:"Write",description:"Create and modify Neon projects, branches, and databases."},{value:"*",label:"Full access",description:"All access - read and manage every Neon resource the connected account can reach."}],getUrlConfiguration:async()=>({docsUrl:"https://neon.com/docs/ai/neon-mcp-server",instructions:"Copy the hosted MCP server URL below. Optional: to narrow access, append ?readonly=true, &projectId=<id>, and/or &category=<groups> (see the Neon MCP docs), then copy the edited URL.",defaultServerUrl:"https://mcp.neon.tech/mcp",optional:!0}),capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Neon connection strings, neon.tech hosts, or @neondatabase/serverless packages","DATABASE_URL/POSTGRES_URL values documented as Neon","README/docs naming Neon as the Postgres provider"],helpText:"Manage Neon projects, branches, databases, and run SQL queries."})});var OhA;var vhA=D(()=>{eA();OhA=V({id:"notion",label:"Notion",iconKey:"notion",defaultServerUrl:"https://mcp.notion.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"notion",callbackPathSegment:"notion",authorizationUrl:"https://mcp.notion.com/authorize",tokenUrl:"https://mcp.notion.com/token",resourceUrl:"https://mcp.notion.com/mcp",dynamicClientRegistration:{registrationEndpoint:"https://mcp.notion.com/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[{value:"default",label:"Default",description:"Access Notion pages, databases, and workspace content via MCP."}],scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},skill:"notion",setupSkill:"notion-setup",evidenceHints:["notion.so URLs, Notion page IDs, or database IDs in docs","NOTION_* environment variables or scripts that call Notion APIs","README/runbooks naming Notion as the wiki or knowledge base"],helpText:"Browse and manage Notion pages, databases, and workspace content. During authorization, choose which pages and databases to share with the connection."})});var ZhA;var WhA=D(()=>{eA();ZhA=V({id:"1password",label:"1Password",iconKey:"onepassword",defaultServerUrl:"https://developer.1password.com/get-started/secure-ai-access",transport:"streamable-http",authMode:"none",availability:"disabled",getUrlConfiguration:async()=>null,evidenceHints:["1Password service-account tokens (ops_...), op CLI usage, or OP_SERVICE_ACCOUNT_TOKEN","1password.com / *.1password.com references, or op:// secret references","README/docs naming 1Password as the secrets manager or vault"],helpText:"Access 1Password via its documented secure AI access options. A general-purpose hosted MCP server is not available today; use the 1Password CLI (op) sandbox preset instead."})});var VhA;var XhA=D(()=>{eA();VhA=V({id:"paper",label:"Paper MCP",iconKey:"paper",defaultServerUrl:"http://127.0.0.1:29979/mcp",transport:"streamable-http",authMode:"none",availability:"disabled",getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["paper.design URLs, Paper Desktop app references, or PAPER_* environment variables","Design files, component libraries, or design-system docs naming Paper","HTML-to-PDF slide or presentation workflows that reference Paper"],helpText:"Read and write Paper design files, including nodes, selections, text content, and design-system elements. Coming soon — Paper's MCP server runs on desktop localhost and can't be reached by hosted Sazabi agents yet."})});var HhA;var KhA=D(()=>{eA();HhA=V({id:"plain",label:"Plain",iconKey:"plain",defaultServerUrl:"https://mcp.plain.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"plain",callbackPathSegment:"plain",authorizationUrl:"https://signin.auth.plain.com/oauth2/authorize",tokenUrl:"https://signin.auth.plain.com/oauth2/token",dynamicClientRegistration:{registrationEndpoint:"https://signin.auth.plain.com/oauth2/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[{value:"openid",required:!0},{value:"offline_access",required:!0}],scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["plain.com links, Plain customer/thread IDs, or PLAIN_* environment variables","Support inbox, customer thread, or tenant docs naming Plain","Code or scripts syncing customers, tenants, or support threads with Plain"],helpText:"Search and manage Plain support threads, customers, and tenants.",skill:"plain",setupSkill:"plain-setup"})});var jhA;var _hA=D(()=>{eA();jhA=V({id:"planetscale",label:"PlanetScale",iconKey:"planetscale",defaultServerUrl:"https://mcp.pscale.dev/mcp/planetscale",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"planetscale",callbackPathSegment:"planetscale",authorizationUrl:"https://app.planetscale.com/oauth/authorize",tokenUrl:"https://auth.planetscale.com/oauth/token",dynamicClientRegistration:{registrationEndpoint:"https://auth.planetscale.com/oauth/registration",tokenEndpointAuthMethod:"client_secret_basic"}},getAvailableScopes:async()=>[{value:"read_databases"},{value:"read_user"},{value:"read_organization"},{value:"write_databases"},{value:"write_organization"}],scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["PlanetScale connection strings, pscale CLI config, or planetscale.com links","PLANETSCALE_* or DATABASE_URL values documented as PlanetScale","README/docs naming PlanetScale for MySQL, branching, or schema changes"],helpText:"Query PlanetScale databases, inspect schema, and browse Insights data.",skill:"planetscale",setupSkill:"planetscale-setup"})});var mhA;var xhA=D(()=>{eA();mhA=V({id:"posthog",label:"PostHog",iconKey:"posthog",defaultServerUrl:"https://mcp.posthog.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"posthog",callbackPathSegment:"posthog",authorizationUrl:"https://oauth.posthog.com/oauth/authorize/",tokenUrl:"https://oauth.posthog.com/oauth/token/",dynamicClientRegistration:{registrationEndpoint:"https://oauth.posthog.com/oauth/register/",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[{value:"query:read"},{value:"insight:read"},{value:"insight:write"},{value:"feature_flag:read"},{value:"feature_flag:write"},{value:"experiment:read"},{value:"experiment:write"},{value:"dashboard:read"},{value:"dashboard:write"},{value:"event_definition:read"},{value:"event_definition:write"},{value:"person:read"},{value:"user:read",required:!0},{value:"user:write"},{value:"organization:read",required:!0},{value:"project:read",required:!0},{value:"project:write"},{value:"survey:read"},{value:"survey:write"},{value:"error_tracking:read"},{value:"logs:read"},{value:"tracing:read"},{value:"error_tracking:write"},{value:"session_recording:read"},{value:"session_recording_playlist:read"},{value:"alert:read"},{value:"activity_log:read"},{value:"annotation:read"},{value:"cohort:read"},{value:"hog_function:read"}],getUrlConfiguration:async()=>({docsUrl:"https://posthog.com/docs/model-context-protocol/faq",instructions:"Copy the hosted MCP server URL below. Optional: to expose only some tools, append ?features=<groups> or ?tools=<names> (see the PostHog MCP docs), then copy the edited URL.",defaultServerUrl:"https://mcp.posthog.com/mcp",optional:!0}),capabilityOverrides:{allowWriteTools:!0},evidenceHints:["posthog-js, posthog-node, POSTHOG_* or NEXT_PUBLIC_POSTHOG_* environment variables","Feature flag, experiment, session replay, or product analytics code using PostHog","README/docs naming PostHog for analytics, flags, experiments, logs, or tracing"],helpText:"Query PostHog analytics, feature flags, and experiments.",skill:"posthog",setupSkill:"posthog-setup"})});var qhA;var dhA=D(()=>{eA();qhA=V({id:"pylon",label:"Pylon",iconKey:"pylon",defaultServerUrl:"https://mcp.usepylon.com",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"pylon",callbackPathSegment:"pylon",authorizationUrl:"https://o.auth.usepylon.com/oauth2/authorize",tokenUrl:"https://o.auth.usepylon.com/oauth2/token",dynamicClientRegistration:{registrationEndpoint:"https://o.auth.usepylon.com/oauth2/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[{value:"openid",required:!0},{value:"offline_access",required:!0}],scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["usepylon.com links, Pylon issue/account IDs, or PYLON_* environment variables","Customer support workflows or account runbooks naming Pylon","Code or scripts syncing support issues, accounts, or contacts with Pylon"],helpText:"Search and manage Pylon support issues, accounts, and contacts.",skill:"pylon",setupSkill:"pylon-setup"})});var phA;var shA=D(()=>{eA();phA=V({id:"railway",label:"Railway",iconKey:"railway",defaultServerUrl:"https://mcp.railway.com",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"railway",callbackPathSegment:"railway",authorizationUrl:"https://backboard.railway.com/oauth/auth",tokenUrl:"https://backboard.railway.com/oauth/token",resourceUrl:"https://mcp.railway.com",dynamicClientRegistration:{registrationEndpoint:"https://backboard.railway.com/oauth/register",tokenEndpointAuthMethod:"none"}},scopesUserSelectable:!1,getAvailableScopes:async()=>[{value:"openid",required:!0},{value:"profile",required:!0},{value:"email",required:!0},{value:"offline_access",required:!0},{value:"workspace:member",label:"Workspace access",description:"Read and manage Railway projects, services, deployments, variables, and logs in the workspaces the connected account belongs to."}],getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},skill:"railway",setupSkill:"railway-setup",evidenceHints:["railway.app / railway.com links, RAILWAY_* environment variables, or a railway.json/railway.toml in the repo","Deploy workflows or runbooks naming Railway as the hosting/PaaS provider","Railway project/service/environment IDs referenced in docs or CI"],helpText:"Manage Railway projects, services, deployments, variables, and logs."})});var AeA;var teA=D(()=>{Jt();eA();AeA=V({id:"render",label:"Render",iconKey:"render",defaultServerUrl:"https://mcp.render.com/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["render.com links, RENDER_* environment variables, or a render.yaml in the repo","Deploy workflows or runbooks naming Render as the hosting/PaaS provider","Render service/deploy IDs referenced in docs or CI"],helpText:"Manage Render services, deploys, environment variables, logs, and metrics.",setupGroups:[{id:"api-key",title:"Create an API key",description:"Create or copy the Render API key Sazabi will send to Render's hosted MCP endpoint.",body:"Create a Render [API key](https://dashboard.render.com/settings/api-keys) in **Account Settings > API Keys**, then paste it below. Note: a Render API key is account-wide and can manage and deploy every service in the account, so treat it as a powerful credential.",fieldKeys:["apiKey"]}],validateCredentials:_IA,normalizeHeaders:jIA})});var geA;var neA=D(()=>{Jt();eA();geA=V({id:"rentahuman",label:"RentAHuman",iconKey:"rentahuman",defaultServerUrl:"https://rentahuman.ai/api/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["rentahuman.ai, RENTAHUMAN_API_KEY environment variables, or RentAHuman API keys","rentahuman-mcp usage or a rentahuman.ai/api/mcp server URL in MCP client config","README/docs naming RentAHuman for hiring humans or human-in-the-loop work"],helpText:"Hire and coordinate human workers for real-world tasks with RentAHuman's hosted MCP server using an API key.",setupGroups:[{id:"api-key",title:"Create an API key",description:"Create or copy the RentAHuman API key Sazabi will send to its hosted MCP endpoint.",body:"Create or copy an API key from the [RentAHuman API keys page](https://rentahuman.ai/account/api-keys), then paste it below. Sazabi stores it securely and sends it as the `X-API-Key` header. Note: this key can hire workers and trigger payments, so keep the per-connection read-only toggle on unless you intend the agent to act.",fieldKeys:["apiKey"]}],validateCredentials:tBA,normalizeHeaders:ABA,skill:"rentahuman",setupSkill:"rentahuman-setup"})});var ieA;var QeA=D(()=>{Jt();eA();ieA=V({id:"resend",label:"Resend",iconKey:"resend",defaultServerUrl:"https://mcp.resend.com/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Resend email API usage, RESEND_API_KEY environment variables, or the resend SDK","resend-mcp usage or a mcp.resend.com server URL in MCP client config","README/docs naming Resend for transactional or marketing email"],helpText:"Send transactional emails and manage domains, contacts, and audiences with Resend's hosted MCP server using your Resend API key.",setupGroups:[{id:"api-key",title:"Create an API key",description:"Create or copy the Resend API key Sazabi will send to Resend's hosted MCP endpoint.",body:"Create or copy an API key from the [Resend dashboard](https://resend.com/api-keys), then paste it below. Choose the key's permission to match what you want the agent to do: **Sending access** (send emails only, the safer choice) or **Full access** (also manage domains, contacts, and audiences). Sazabi stores it securely and sends it as the `Authorization: Bearer` token to Resend's MCP endpoint (`https://mcp.resend.com/mcp`).",fieldKeys:["apiKey"]}],validateCredentials:hBA,normalizeHeaders:BBA,skill:"resend",setupSkill:"resend-setup"})});var oeA;var IeA=D(()=>{Jt();eA();oeA=V({id:"respan",label:"Respan",iconKey:"respan",defaultServerUrl:"https://mcp.respan.ai/api/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Respan / Keywords AI observability usage, RESPAN_API_KEY environment variables, or the respan-ai / keywordsai SDK","respan-mcp usage or a mcp.respan.ai server URL in MCP client config","README/docs naming Respan or Keywords AI for LLM logs, traces, or prompt management"],helpText:"Query LLM request logs, traces, prompts, and customer data from your Respan account using Respan's hosted MCP server and your Respan API key.",setupGroups:[{id:"api-key",title:"Create an API key",description:"Create or copy the Respan API key Sazabi will send to Respan's hosted MCP endpoint.",body:"Create or copy an API key from the [Respan dashboard](https://platform.respan.ai/platform/api/api-keys), then paste it below. Sazabi stores it securely and sends it as the `Authorization: Bearer` token to Respan's MCP endpoint (`https://mcp.respan.ai/api/mcp`).",fieldKeys:["apiKey"]}],validateCredentials:CBA,normalizeHeaders:eBA,skill:"respan",setupSkill:"respan-setup"})});var BeA;var heA=D(()=>{eA();BeA=V({id:"salesforce",label:"Salesforce",iconKey:"salesforce",defaultServerUrl:"https://api.salesforce.com/platform/mcp/v1/platform/sobject-all",transport:"streamable-http",authMode:"oauth",availability:"disabled",oauth:{providerConfigKey:"salesforce",callbackPathSegment:"salesforce",authorizationUrl:"https://login.salesforce.com/services/oauth2/authorize",tokenUrl:"https://login.salesforce.com/services/oauth2/token"},scopesUserSelectable:!1,getAvailableScopes:async()=>[{value:"mcp_api",label:"MCP API access",description:"Access Salesforce data and metadata (sObjects, Apex invocable actions, Flows) through the hosted MCP server. Salesforce hosted MCP External Client Apps require the MCP-specific `mcp_api` scope."},{value:"refresh_token",label:"Offline access",description:"Refresh the access token without requiring the user to re-authenticate.",required:!0}],capabilityOverrides:{allowWriteTools:!0},setupGroups:[{id:"external-client-app",title:"Register an External Client App in Salesforce",description:"Salesforce hosted MCP servers do not support automatic client registration. An admin must create an External Client App (ECA) in the org and enable it for the hosted MCP server.",body:["1. In Salesforce Setup, open **App Manager** and create a new **External Client App**.","2. Enable OAuth, add the **mcp_api** and **refresh_token (offline access)** scopes, and require PKCE.","3. Set the callback URL to the Sazabi Salesforce MCP callback URL shown on this page.","4. Enable the app for your hosted MCP server under **Setup → MCP Servers**.","5. Provide the generated **Consumer Key (Client ID)** and **Consumer Secret (Client Secret)** to your Sazabi deployment configuration."].join(`
|
|
8707
|
-
`)}],evidenceHints:["force.com / my.salesforce.com URLs, SALESFORCE_* or SFDC_* environment variables, or sf/sfdx CLI usage","jsforce, simple-salesforce, or @salesforce packages","README/runbooks naming Salesforce as the CRM or system of record"],helpText:"Query Salesforce data and metadata, and run Apex invocable actions and Flows exposed by a hosted MCP server. Coming soon — a Salesforce admin registers an External Client App in your org and Sazabi provisions its credentials, so it isn't self-serve connectable yet."})});var eeA;var CeA=D(()=>{eA();eeA=V({id:"secureframe",label:"Secureframe",iconKey:"secureframe",defaultServerUrl:"https://mcp.secureframe.com",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"secureframe",callbackPathSegment:"secureframe",authorizationUrl:"https://mcp.secureframe.com/oauth/authorize",tokenUrl:"https://mcp.secureframe.com/oauth/token",resourceUrl:"https://mcp.secureframe.com",dynamicClientRegistration:{registrationEndpoint:"https://mcp.secureframe.com/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[{value:"mcp",label:"MCP Access",description:"Query and manage Secureframe compliance data, controls, tests, vendors, risks, and framework requirements."}],scopesUserSelectable:!1,regions:[{label:"United States (US)",serverUrl:"https://mcp.secureframe.com"},{label:"United Kingdom (UK)",serverUrl:"https://mcp-uk.secureframe.com",authorizationUrl:"https://mcp-uk.secureframe.com/oauth/authorize",tokenUrl:"https://mcp-uk.secureframe.com/oauth/token",resourceUrl:"https://mcp-uk.secureframe.com",dynamicClientRegistration:{registrationEndpoint:"https://mcp-uk.secureframe.com/register",tokenEndpointAuthMethod:"none"}}],capabilityOverrides:{allowWriteTools:!0},evidenceHints:["secureframe.com URLs, SECUREFRAME_API_KEY / SECUREFRAME_API_SECRET environment variables","SOC 2, ISO 27001, HIPAA, PCI DSS, GDPR, or NIST compliance frameworks and controls","README/docs or compliance runbooks naming Secureframe for automated compliance and continuous monitoring"],helpText:"Query and manage Secureframe compliance data, controls, automated tests, vendors, risks, and framework requirements. Choose the US or UK region when connecting.",skill:"secureframe",setupSkill:"secureframe-setup"})});var ceA;var EeA=D(()=>{eA();ceA=V({id:"sentry",label:"Sentry",iconKey:"sentry",defaultServerUrl:"https://mcp.sentry.dev/mcp",serverUrlPathSuffixMaxSegments:2,transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"sentry",callbackPathSegment:"sentry",authorizationUrl:"https://mcp.sentry.dev/oauth/authorize",tokenUrl:"https://mcp.sentry.dev/oauth/token",useServerUrlAsResource:!0,dynamicClientRegistration:{registrationEndpoint:"https://mcp.sentry.dev/oauth/register",tokenEndpointAuthMethod:"none"}},scopesUserSelectable:!1,getAvailableScopes:async()=>[{value:"org:read"},{value:"project:write"},{value:"team:write"},{value:"event:write"}],getUrlConfiguration:async()=>({docsUrl:"https://mcp.sentry.dev/",instructions:"Copy the hosted MCP server URL below. Optional: to scope this connection to one organization or project, copy a path-scoped URL from the Sentry MCP page (e.g. .../mcp/your-org).",defaultServerUrl:"https://mcp.sentry.dev/mcp",optional:!0}),capabilityOverrides:{allowWriteTools:!0},evidenceHints:["@sentry packages, sentry.properties, SENTRY_* environment variables, or sentry-cli usage","Sentry.init calls, release/deploy automation, or Sentry alert docs","README/docs naming Sentry as the error tracking provider"],helpText:"Browse Sentry organizations, teams, projects, and events."})});var yeA;var DeA=D(()=>{Jt();eA();yeA=V({id:"signoz",label:"SigNoz",iconKey:"signoz",defaultServerUrl:"https://mcp.us.signoz.cloud/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["SigNoz config, SIGNOZ_* environment variables, or signoz.io links","OpenTelemetry Collector exporting to SigNoz, or a signoz docker-compose / self-hosted deployment","README/docs naming SigNoz for metrics, logs, traces, alerts, or dashboards"],helpText:"Query SigNoz metrics, logs, traces, alerts, and dashboards to investigate production issues.",setupGroups:[{id:"instance",title:"Find your SigNoz instance",description:"Point Sazabi at the SigNoz instance whose telemetry you want to query.",body:"For SigNoz Cloud, use the regional MCP endpoint for your account, such as `https://mcp.us.signoz.cloud/mcp` (replace the region as needed). For self-hosted SigNoz, use your instance's MCP endpoint and set the SigNoz base URL below so the server knows which instance to target.",fieldKeys:["signozUrl"]},{id:"api-key",title:"Create an API key",description:"Create or copy the SigNoz API key Sazabi will send to SigNoz's MCP endpoint.",body:"In SigNoz, go to **Settings > API Keys** and create or copy an API key. Alert, dashboard, and notification-channel tools require an admin-level key. Paste it below.",fieldKeys:["apiKey"]}],validateCredentials:xIA,normalizeHeaders:mIA})});var weA;var aeA=D(()=>{eA();weA=V({id:"slack",label:"Slack",iconKey:"slack",defaultServerUrl:"https://mcp.slack.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"disabled",oauth:{providerConfigKey:"slack",callbackPathSegment:"slack",authorizationUrl:"https://slack.com/oauth/v2_user/authorize",tokenUrl:"https://slack.com/api/oauth.v2.user.access"},getAvailableScopes:async()=>[{value:"search:read.public"},{value:"search:read.private"},{value:"search:read.mpim"},{value:"search:read.im"},{value:"search:read.files"},{value:"search:read.users"},{value:"canvases:read"},{value:"users:read"},{value:"users:read.email"}],getUrlConfiguration:async()=>null,capabilityOverrides:{defaultUnavailableReason:"write_blocked"},evidenceHints:["Slack app manifests, bot/webhook URLs, SLACK_* environment variables, or slack.com links","Runbooks that route incidents, alerts, or deploy notices through Slack","Code or docs naming Slack channels for operational triage"],helpText:"Browse Slack messages, files, and threads. Coming soon — requires backend OAuth plumbing for user_scope and isn't self-serve connectable yet.",skill:"slack",setupSkill:"slack-setup"})});var reA;var beA=D(()=>{eA();reA=V({id:"stripe",label:"Stripe MCP",iconKey:"stripe",defaultServerUrl:"https://mcp.stripe.com",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"stripe",callbackPathSegment:"stripe",authorizationUrl:"https://access.stripe.com/mcp/oauth2/authorize",tokenUrl:"https://access.stripe.com/mcp/oauth2/token",resourceUrl:"https://mcp.stripe.com",dynamicClientRegistration:{registrationEndpoint:"https://access.stripe.com/mcp/oauth2/register",tokenEndpointAuthMethod:"none"},defaultAccessTokenTtlSeconds:21600},getAvailableScopes:async()=>[{value:"mcp",label:"MCP access",description:"Access the Stripe MCP server tools for the connected account.",required:!0}],scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Stripe dashboard URLs, `sk_`/`rk_`/`pk_` API keys, or Stripe object IDs (cus_, pi_, ch_)","STRIPE_* environment variables or code that imports the `stripe` SDK","README/runbooks naming Stripe for billing, payments, or subscriptions"],helpText:"Query and manage Stripe payments, customers, and billing."})});var NeA;var ueA=D(()=>{eA();NeA=V({id:"supabase",label:"Supabase",iconKey:"supabase",defaultServerUrl:"https://mcp.supabase.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"supabase",callbackPathSegment:"supabase",authorizationUrl:"https://api.supabase.com/v1/oauth/authorize",tokenUrl:"https://api.supabase.com/v1/oauth/token",dynamicClientRegistration:{registrationEndpoint:"https://api.supabase.com/platform/oauth/apps/register",tokenEndpointAuthMethod:"client_secret_post"}},scopesUserSelectable:!1,getAvailableScopes:async()=>[{value:"analytics:read"},{value:"auth:read"},{value:"auth:write"},{value:"database:read"},{value:"database:write"},{value:"domains:read"},{value:"domains:write"},{value:"edge_functions:read"},{value:"edge_functions:write"},{value:"environment:read"},{value:"environment:write"},{value:"organizations:read"},{value:"projects:read"},{value:"projects:write"},{value:"rest:read"},{value:"rest:write"},{value:"secrets:read"},{value:"secrets:write"},{value:"storage:read"}],getUrlConfiguration:async()=>({docsUrl:"https://supabase.com/docs/guides/getting-started/mcp#step-2-configure-your-ai-tool",instructions:"Choose your project and options in the Supabase configuration panel, then copy the generated Server URL.",defaultServerUrl:"https://mcp.supabase.com/mcp",optional:!0}),capabilityOverrides:{allowWriteTools:!0},evidenceHints:["supabase/ directory, supabase/config.toml, or @supabase packages","SUPABASE_* or NEXT_PUBLIC_SUPABASE_* environment variables","README/docs naming Supabase for Postgres, Auth, Storage, or Edge Functions"],helpText:"Manage Supabase organizations, projects, databases, and run SQL.",skill:"supabase",setupSkill:"supabase-setup"})});var UeA;var FeA=D(()=>{eA();UeA=V({id:"superhuman",label:"Superhuman",iconKey:"superhuman",defaultServerUrl:"https://mcp.mail.superhuman.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"superhuman",callbackPathSegment:"superhuman",authorizationUrl:"https://mcp.auth.mail.superhuman.com/oauth2/authorize",tokenUrl:"https://mcp.auth.mail.superhuman.com/oauth2/token",dynamicClientRegistration:{registrationEndpoint:"https://mcp.auth.mail.superhuman.com/oauth2/register",tokenEndpointAuthMethod:"none"}},scopesUserSelectable:!1,getAvailableScopes:async()=>[{value:"email",required:!0},{value:"offline_access",required:!0},{value:"openid",required:!0},{value:"profile",required:!0}],getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Superhuman mail links, SUPERHUMAN_* environment variables, or support workflows naming Superhuman","Customer communication runbooks that depend on email search or drafting","Docs naming Superhuman Mail for sales, support, or founder-led customer comms"],helpText:"Search, draft, send, and triage emails in Superhuman Mail."})});var LeA;var SeA=D(()=>{Jt();eA();LeA=V({id:"the-context-company",label:"The Context Company",iconKey:"the-context-company",defaultServerUrl:"https://api.thecontext.company/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!1},evidenceHints:["The Context Company, context company, or context observability references","insight_search, get_agent_runs, or get_agent_sessions tool usage","THE_CONTEXT_COMPANY_API_KEY or api.thecontext.company in MCP configuration"],helpText:"Query agent insights, runs, and sessions through The Context Company's read-only hosted MCP server.",setupGroups:[{id:"api-key",title:"Create a read-only API key",description:"Create the API key The Context Company's hosted MCP server will use.",body:"Generate a read-only API key on The Context Company's [Access Data page](https://www.thecontextcompany.com/prod/mcp-and-api), then paste the raw key below. Sazabi sends it as `Authorization: Bearer <key>` to `https://api.thecontext.company/mcp`.",fieldKeys:["apiKey"]}],validateCredentials:ZIA,normalizeHeaders:vIA,skill:"the-context-company",setupSkill:"the-context-company-setup"})});var leA;var MeA=D(()=>{eA();leA=V({id:"vercel",label:"Vercel",iconKey:"vercel",defaultServerUrl:"https://mcp.vercel.com",transport:"streamable-http",authMode:"oauth",availability:"disabled",oauth:{providerConfigKey:"vercel",callbackPathSegment:"vercel",authorizationUrl:"https://vercel.com/oauth/authorize",tokenUrl:"https://vercel.com/api/login/oauth/token",resourceUrl:"https://mcp.vercel.com",dynamicClientRegistration:{registrationEndpoint:"https://vercel.com/api/login/oauth/register",tokenEndpointAuthMethod:"none"}},scopesUserSelectable:!1,getAvailableScopes:async()=>[{value:"openid",required:!0},{value:"offline_access",required:!0}],getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["vercel.com links, VERCEL_* environment variables, or a vercel.json in the repo","Deploy workflows or runbooks naming Vercel as the frontend/hosting provider","Vercel project/deployment IDs or preview URLs referenced in docs or CI"],helpText:"Manage Vercel projects, deployments, and access Vercel platform documentation. Coming soon — Vercel's hosted MCP only authorizes allowlisted clients and Sazabi is pending approval, so it isn't connectable yet."})});var YeA;var $eA=D(()=>{Jt();eA();YeA=V({id:"x",label:"X",iconKey:"x",defaultServerUrl:"https://api.x.com/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{readOnlyToolNames:["search_news","get_news","get_trends_by_woeid","get_posts_by_ids","get_posts_counts_recent","search_posts_all","get_posts_by_id","get_posts_liking_users","get_posts_quoted_posts","get_posts_reposted_by","get_users_by_usernames","get_users_by_username","get_users_me","search_users","get_users_by_id","get_users_bookmarks","get_users_bookmark_folders","get_users_bookmarks_by_folder_id","get_users_mentions","get_users_timeline","get_users_posts"]},evidenceHints:["X (Twitter) API usage, X_BEARER_TOKEN, or TWITTER_* environment variables","twitter-api-v2, tweepy, or other X/Twitter API client packages","README/docs naming the X API, X Developer Platform, or tweet automation"],helpText:"Search X posts and access real-time X data using your app's app-only Bearer Token.",setupGroups:[{id:"developer-app",title:"Open the X Developer Portal",description:"Use an X developer project/app with access to the X API v2.",body:"Go to the [X Developer Portal](https://developer.x.com/en/portal/dashboard), open the project and app you want Sazabi to use, and confirm the app has access to the API tiers you need. The hosted MCP server lives at `https://api.x.com/mcp`."},{id:"bearer-token",title:"Copy the app's Bearer Token",description:"Copy the app-only Bearer Token the hosted MCP server will use.",body:"In your app's **Keys and tokens**, find the app-only **Bearer Token** and copy it (regenerate it if you don't have it saved). This is the app-only token, not a user OAuth 2.0 access token. Paste the raw token into Sazabi — Sazabi adds the `Bearer ` prefix and sends it in the `Authorization` header.",fieldKeys:["accessToken"]}],validateCredentials:WIA,normalizeHeaders:OIA,skill:"x",setupSkill:"x-setup"})});var GeA,mRt;var JeA=D(()=>{UBA();LBA();lBA();YBA();s0();s0();GBA();TBA();PBA();zBA();vBA();WBA();XBA();KBA();_BA();xBA();dBA();sBA();thA();nhA();QhA();IhA();hhA();ChA();EhA();DhA();ahA();bhA();uhA();FhA();ShA();MhA();$hA();GhA();ThA();PhA();zhA();vhA();WhA();XhA();KhA();_hA();xhA();dhA();shA();teA();neA();QeA();IeA();heA();CeA();EeA();DeA();aeA();beA();ueA();FeA();SeA();MeA();$eA();GeA=[NeA,ghA,ihA,uBA,FBA,SBA,MBA,$BA,kBA,JBA,RBA,fBA,OBA,ZBA,HBA,jBA,mBA,qBA,VBA,pBA,AhA,ohA,BhA,ehA,chA,yhA,whA,rhA,NhA,UhA,LhA,lhA,YhA,khA,JhA,RhA,fhA,OhA,ZhA,VhA,HhA,jhA,mhA,qhA,phA,geA,AeA,ieA,oeA,BeA,eeA,ceA,yeA,weA,reA,UeA,LeA,leA,YeA],mRt=new Map(GeA.map((A)=>[A.id,A]))});var TeA=()=>{};var ReA=()=>{};var PeA=()=>{};var feA=()=>{};var zeA=()=>{};var OeA=()=>{};var veA=()=>{};var ZeA=()=>{};var WeA=()=>{};var VeA=()=>{};var XeA=()=>{};var HeA=()=>{};var KeA=()=>{};var jeA=()=>{};var _eA=()=>{};var meA=()=>{};var xeA=()=>{};var qeA=()=>{};var deA=()=>{};var peA=()=>{};var seA=()=>{};var ACA=()=>{};var tCA=()=>{};var gCA=()=>{};var nCA=()=>{};var iCA=()=>{};var QCA=()=>{};var oCA=()=>{};var ICA=()=>{};var BCA=()=>{};var hCA=()=>{};var eCA=()=>{};var CCA=()=>{};var cCA=()=>{};var ECA=()=>{};var yCA=()=>{};var DCA=()=>{};var wCA=()=>{};var aCA=()=>{};var rCA=()=>{};var bCA=()=>{};var NCA=()=>{};var uCA=()=>{};var UCA=()=>{};var FCA=D(()=>{TeA();ReA();PeA();feA();zeA();OeA();veA();ZeA();WeA();VeA();XeA();HeA();KeA();jeA();_eA();meA();xeA();qeA();deA();peA();seA();ACA();tCA();gCA();nCA();iCA();QCA();oCA();ICA();BCA();hCA();eCA();CCA();cCA();ECA();yCA();DCA();wCA();aCA();rCA();bCA();NCA();uCA();UCA()});var LCA=D(()=>{s0()});var SCA=()=>{};var lCA=D(()=>{p_();qa();kIA();Jt();DBA();wBA();JeA();wf();FCA();LCA();SCA()});var MCA,R3A,YCA,P3A,$CA,af,kCA,GCA,ro,JCA,TCA,RCA,Ne,PCA,fCA,ue,zCA,OCA,Ue,vCA,f3A,ZCA,AN,WCA,VCA,XCA,HCA,Fe,KCA,jCA,Le,_CA,mCA,Se,rf,bf,xCA,qCA,le,dCA,pCA,Me,sCA,z3A,Ye,AcA,tcA,$e,gcA,ncA,ke,icA,QcA,Ge,O3A;var Nf=D(()=>{lCA();TA();jA();MCA=["configured","authorizing","connected","error"],R3A=I.enum(MCA),YCA=["preset","custom"],P3A=I.enum(YCA),$CA=["streamable-http","sse"],af=I.enum($CA),kCA=["none","headers","oauth","aws-sigv4"],GCA=I.enum(kCA),ro=I.object({connectionId:I.string().uuid().describe("Connection ID."),connectionKey:I.string().describe("Stable key used to reference this connector in tool calls."),providerId:I.string().describe('Provider identifier, e.g. "linear".'),displayName:I.string().describe("Human-readable connector name."),source:P3A.describe("Whether the connector is a built-in preset or a custom server."),installStatus:R3A.describe("Current connection lifecycle status."),authMode:GCA.describe("Authentication mode."),transport:af.describe("Transport protocol."),serverUrl:I.string().describe("MCP server URL."),readOnly:I.boolean().describe("Whether the connector is restricted to read-only tools."),management:Mk.describe("Lifecycle owner and supported connector mutations."),enabledToolCount:I.number().int().nonnegative().describe("Number of tools enabled and available for this connector."),connectedAt:I.string().datetime().nullable().describe("When the connector last became connected, if ever."),createdAt:I.string().datetime(),updatedAt:I.string().datetime()}),JCA=I.object({name:I.string().describe("Tool name as invoked."),title:I.string().describe("Human-readable tool title."),description:I.string().describe("Tool description."),isReadOnly:I.boolean().describe("Whether the tool is considered read-only."),enabled:I.boolean().describe("Whether the tool is enabled and available given the connector config.")}),TCA=I.object({projectId:I.string().uuid().optional().describe("Project to list connectors for. Auto-filled from SDK context when omitted."),connectedOnly:I.union([I.boolean(),I.stringbool()]).optional().describe("When true, only return connectors that are connected.")}),RCA=I.object({connectors:I.array(ro)}),Ne=L({operationId:"mcpConnectors.list",description:"List configured MCP connectors within one project with provider, status, and enabled-tool count.",backend:"api",route:{method:"GET",path:"/mcp-connectors",tags:["MCP Connectors"]},input:TCA,output:RCA,pagination:"none",async:"sync"}),PCA=I.object({connectionId:I.string().uuid().describe("Connection ID to fetch."),projectId:I.string().uuid().optional().describe("Project the connector belongs to. Auto-filled from SDK context when omitted.")}),fCA=I.object({connector:ro}),ue=L({operationId:"mcpConnectors.get",description:"Get one configured MCP connector by connection ID.",backend:"api",route:{method:"GET",path:"/mcp-connectors/{connectionId}",tags:["MCP Connectors"]},input:PCA,output:fCA,pagination:"none",async:"sync"}),zCA=I.object({connectionId:I.string().uuid().describe("Connection ID to inspect."),projectId:I.string().uuid().optional().describe("Project the connector belongs to. Auto-filled from SDK context when omitted.")}),OCA=I.object({connector:ro,tools:I.array(JCA)}),Ue=L({operationId:"mcpConnectors.details",description:"Inspect one MCP connector's tool surface, including each tool's name, description, and read-only status.",backend:"api",route:{method:"GET",path:"/mcp-connectors/{connectionId}/details",tags:["MCP Connectors"]},input:zCA,output:OCA,pagination:"none",async:"sync"}),vCA=I.object({providerId:I.string().describe('Provider identifier, e.g. "linear".'),label:I.string().describe("Human-readable provider name."),authMode:GCA.describe("Authentication mode."),availability:I.enum(gh).describe("Whether the provider is enabled or coming soon."),setupSkill:I.string().nullable().describe("Markdown setup skill for AI agents. Null when no skill is available.")}),f3A=I.object({}),ZCA=I.object({providers:I.array(vCA)}),AN=L({operationId:"mcpConnectors.listProviders",description:"List all supported MCP connector providers with their auth mode and setup skill.",backend:"api",route:{method:"GET",path:"/mcp-connectors/providers",tags:["MCP Connectors"]},input:f3A,output:ZCA,pagination:"none",async:"sync"}),WCA=I.object({connectionKey:I.string().describe("Stable key used to call this connector."),displayName:I.string().describe("Human-readable connector name."),providerId:I.string().describe('Provider identifier, e.g. "linear".'),toolCount:I.number().int().nonnegative().describe("Number of executable tools on this connector.")}),VCA=I.object({connectionKey:I.string().describe("Connector that exposes this tool."),toolName:I.string().describe("Tool name as invoked."),providerId:I.string().describe('Provider identifier, e.g. "linear".'),displayName:I.string().describe("Human-readable connector name."),isReadOnly:I.boolean().describe("Whether the tool is considered read-only."),description:I.string().describe("Tool description from the stored snapshot."),score:I.number().describe("BM25 rank score. Zero when enumerating a namespace."),inputSchema:I.record(I.string(),I.unknown()).optional().describe("JSON Schema for the tool's arguments, when requested.")}),XCA=I.object({projectId:I.string().uuid().optional().describe("Project to search connectors in. Auto-filled from SDK context when omitted."),query:I.string().optional().describe("Free-text query over tool names, titles, connector keys, and descriptions. Omit or empty to list connectors, or to enumerate one connector when namespace is set."),namespace:I.string().min(1).optional().describe("Restrict results to one connectionKey or providerId."),limit:I.coerce.number().int().min(1).max(100).default(10).describe("Maximum number of connectors or tool hits to return."),offset:I.coerce.number().int().min(0).default(0).describe("Number of connectors or tool hits to skip."),includeInputSchema:I.union([I.boolean(),I.stringbool()]).optional().describe("When true, tool hits include inputSchema so a caller can execute without a describe round-trip.")}),HCA=I.object({kind:I.enum(["connectors","tools"]).describe("connectors when the query is empty and no namespace is set; tools otherwise."),total:I.number().int().nonnegative().describe("Total matches before limit and offset."),connectors:I.array(WCA).describe("Connector index. Empty when kind is tools."),tools:I.array(VCA).describe("Ranked or enumerated tool hits. Empty when kind is connectors.")}),Fe=L({operationId:"mcpConnectors.search",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.",backend:"api",route:{method:"GET",path:"/mcp-connectors/tools/search",tags:["MCP Connectors"]},input:XCA,output:HCA,pagination:"none",async:"sync"}),KCA=I.object({projectId:I.string().uuid().optional().describe("Project the connector belongs to. Auto-filled from SDK context when omitted."),connectionKey:I.string().min(1).describe("Connector key from search or mcpConnectors.list."),toolName:I.string().min(1).describe("Tool name as invoked.")}),jCA=I.object({connectionKey:I.string().describe("Connector that exposes this tool."),toolName:I.string().describe("Tool name as invoked."),providerId:I.string().describe('Provider identifier, e.g. "linear".'),displayName:I.string().describe("Human-readable connector name."),title:I.string().describe("Human-readable tool title."),description:I.string().describe("Tool description from the stored snapshot."),isReadOnly:I.boolean().describe("Whether the tool is considered read-only."),inputSchema:I.record(I.string(),I.unknown()).describe("JSON Schema for the tool's arguments.")}),Le=L({operationId:"mcpConnectors.describe",description:"Load one executable third-party MCP connector tool, including its input schema.",backend:"api",route:{method:"GET",path:"/mcp-connectors/tools/describe",tags:["MCP Connectors"]},input:KCA,output:jCA,pagination:"none",async:"sync"}),_CA=I.object({projectId:I.string().uuid().optional().describe("Project the connector belongs to. Auto-filled from SDK context when omitted."),connectionKey:I.string().min(1).describe("Connector key from search or mcpConnectors.list."),toolName:I.string().min(1).describe("Tool name as invoked."),arguments:I.record(I.string(),I.unknown()).optional().describe("Arguments matching the tool's input schema.")}),mCA=I.discriminatedUnion("ok",[I.object({ok:I.literal(!0),connectionKey:I.string().describe("Connector that ran the tool."),toolName:I.string().describe("Tool name as invoked."),result:I.unknown().describe("Vendor tool result payload."),structuredContent:I.unknown().optional().describe("Structured content from the vendor when present."),content:I.array(I.record(I.string(),I.unknown())).describe("Raw MCP content parts from the vendor."),text:I.string().nullable().describe("Concatenated text content, if any.")}),I.object({ok:I.literal(!1),code:I.enum(["TOOL_NOT_ENABLED","READ_ONLY","MCP_ERROR"]).describe("Why the tool did not run."),message:I.string().describe("Caller-facing error message.")})]),Se=L({operationId:"mcpConnectors.call",description:"Invoke one executable third-party MCP connector tool using that connection's stored credential.",backend:"api",route:{method:"POST",path:"/mcp-connectors/tools/call",tags:["MCP Connectors"]},input:_CA,output:mCA,pagination:"none",async:"sync"}),rf=I.object({id:I.string().min(1).describe("Stable ID for this header (must be unique within the connector)."),name:I.string().trim().min(1).describe("HTTP header name."),value:I.string().min(1).describe("HTTP header value (passed verbatim).")}),bf=I.object({accessKeyId:I.string().trim().min(1).describe("AWS access key ID."),secretAccessKey:I.string().min(1).describe("AWS secret access key."),sessionToken:I.string().min(1).optional().describe("Optional session token for temporary credentials."),region:I.string().trim().min(1).describe("AWS region.")}),xCA=I.object({projectId:I.string().uuid().optional().describe("Project to create the connector in. Auto-filled from SDK context when omitted."),serverUrl:I.string().url().describe("MCP server URL (must be https)."),transport:af.describe("Transport protocol."),headers:I.array(rf).optional().describe("HTTP headers to send with each request."),awsSigV4:bf.optional().describe("AWS SigV4 credentials for AWS MCP servers."),providerId:I.string().min(1).describe("Built-in preset provider ID (for example, linear or datadog)."),readOnly:I.boolean().optional().describe("Restrict the connector to read-only tools. Defaults to false.")}),qCA=I.object({connector:ro}),le=L({operationId:"mcpConnectors.create",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.",backend:"api",route:{method:"POST",path:"/mcp-connectors",tags:["MCP Connectors"],successStatus:201},input:xCA,output:qCA,pagination:"none",async:"sync"}),dCA=I.object({connectionId:I.string().uuid().describe("Connection ID to update."),projectId:I.string().uuid().optional().describe("Project the connector belongs to. Auto-filled from SDK context when omitted."),serverUrl:I.string().url().optional().describe("New MCP server URL."),transport:af.optional().describe("New transport protocol."),headers:I.array(rf).optional().describe("Complete replacement header set. Replaces all existing headers."),awsSigV4:bf.optional().describe("Replacement AWS SigV4 credentials. Mutually exclusive with headers.")}),pCA=I.object({connector:ro}),Me=L({operationId:"mcpConnectors.update",description:"Deprecated. Preset MCP connector updates are no longer supported via the public API; disconnect and reconnect instead.",backend:"api",route:{method:"PATCH",path:"/mcp-connectors/{connectionId}",tags:["MCP Connectors"]},input:dCA,output:pCA,pagination:"none",async:"sync"}),sCA=I.object({connectionId:I.string().uuid().describe("Connection ID to disconnect."),projectId:I.string().uuid().optional().describe("Project the connector belongs to. Auto-filled from SDK context when omitted.")}),z3A=I.void(),Ye=L({operationId:"mcpConnectors.disconnect",description:"Disconnect and permanently remove an MCP connector.",backend:"api",route:{method:"DELETE",path:"/mcp-connectors/{connectionId}",tags:["MCP Connectors"],successStatus:204},input:sCA,output:z3A,pagination:"none",async:"sync"}),AcA=I.object({connectionId:I.string().uuid().describe("Connection ID to update."),projectId:I.string().uuid().optional().describe("Project the connector belongs to. Auto-filled from SDK context when omitted."),readOnly:I.boolean().describe("True to restrict to read-only tools; false to allow all enabled tools.")}),tcA=I.object({connector:ro}),$e=L({operationId:"mcpConnectors.setReadOnly",description:"Toggle the read-only restriction on an MCP connector.",backend:"api",route:{method:"PATCH",path:"/mcp-connectors/{connectionId}/read-only",tags:["MCP Connectors"]},input:AcA,output:tcA,pagination:"none",async:"sync"}),gcA=I.object({projectId:I.string().uuid().optional().describe("Project to install into. Auto-filled from SDK context when omitted."),providerId:I.string().min(1).describe('Provider ID to install, e.g. "linear".'),requestedScopes:I.array(I.string()).optional().describe("Scopes to request. Defaults to the provider's recommended scope set."),serverUrl:I.string().url().optional().describe("Server URL for multi-region providers; defaults to the provider's primary server."),readOnly:I.boolean().optional().describe("Restrict the connector to read-only tools after install. Defaults to false."),returnTo:I.string().optional().describe("Path to redirect the user to after OAuth completes.")}),ncA=I.object({authorizationUrl:I.string().describe("Authorization URL to open in the user's browser."),connectionId:I.string().uuid().describe("Connection ID to poll for completion via getMcpOAuthInstallAttempt."),expiresAt:I.string().datetime().describe("When the OAuth authorization attempt expires.")}),ke=L({operationId:"mcpConnectors.beginOAuthInstall",description:"Begin an OAuth browser flow to install a preset MCP connector. Opens an authorization URL in the user's browser; poll getMcpOAuthInstallAttempt with the returned connectionId to check completion.",backend:"api",route:{method:"POST",path:"/mcp-connectors/oauth/begin",tags:["MCP Connectors"],successStatus:201},input:gcA,output:ncA,pagination:"none",async:"sync"}),icA=I.object({connectionId:I.string().uuid().describe("Connection ID returned by beginMcpOAuthInstall."),projectId:I.string().uuid().optional().describe("Project the connection belongs to. Auto-filled from SDK context when omitted.")}),QcA=I.object({status:I.enum(["authorizing","connected","error"]).describe("Current install status."),connector:ro.optional().describe("Connector details once connected or in error state.")}),Ge=L({operationId:"mcpConnectors.getOAuthInstallAttempt",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.",backend:"api",route:{method:"GET",path:"/mcp-connectors/oauth/attempts/{connectionId}",tags:["MCP Connectors"]},input:icA,output:QcA,pagination:"none",async:"sync"}),O3A={list:Ne.contract,get:ue.contract,details:Ue.contract,listProviders:AN.contract,search:Fe.contract,describe:Le.contract,call:Se.contract,create:le.contract,update:Me.contract,disconnect:Ye.contract,setReadOnly:$e.contract,beginOAuthInstall:ke.contract,getOAuthInstallAttempt:Ge.contract}});var bo,v3A,Z3A,W3A,V3A,X3A,H3A,K3A,uf,f1t;var tN=D(()=>{TA();jA();bo=I.enum(["admin","member"]),v3A=I.object({id:I.string().min(1),name:I.string(),slug:I.string(),logo:I.string().nullable().optional(),role:bo}),Z3A=I.object({id:I.string().min(1),name:I.string().nullable(),email:I.string().email()}),W3A=I.object({credentialType:I.literal("user"),user:Z3A,activeOrganizationId:I.string().min(1).nullable(),authorizedOrganizationId:I.string().min(1).nullable(),authorizedProjectId:I.string().min(1).nullable(),organizations:I.array(v3A).describe("Organizations the user belongs to, including membership role.")}),V3A=I.object({credentialType:I.literal("secret"),organization:I.object({id:I.string().min(1),name:I.string(),slug:I.string(),logo:I.string().nullable().optional()}),keyName:I.string()}),X3A=I.object({credentialType:I.literal("partner"),superorganization:I.object({id:I.string().uuid(),name:I.string()})}),H3A=I.object({}),K3A=I.discriminatedUnion("credentialType",[W3A,V3A,X3A]),uf=L({operationId:"me.get",description:"Return the identity and available context for the current credential.",backend:"api",route:{method:"GET",path:"/me",tags:["Auth"]},input:H3A,output:K3A,pagination:"none",async:"sync"}),f1t=uf.contract});var ocA,IcA,BcA,j3A,_3A,m3A,x3A,q3A,d3A,Uf,Ff,Lf,p3A,s3A,A7A,t7A,g7A,n7A,Sf,lf,Mf,W1t;var hcA=D(()=>{TA();jA();tN();ocA=I.object({membershipId:I.string().min(1).describe("Organization membership record ID."),userId:I.string().min(1).describe("User ID for the organization member."),name:I.string().nullable().describe("Display name for the member, when available."),email:I.string().email().describe("Email address for the member."),imageUrl:I.string().nullable().describe("Profile image URL for the member, when available."),role:bo.describe("Organization role."),createdAt:I.string().datetime().describe("When the membership was created.")}),IcA=I.object({id:I.string().min(1).describe("Invitation ID."),email:I.string().email().describe("Invited email address."),role:bo.describe("Role the invitee will receive when they accept."),status:I.string().min(1).describe('Invitation status (e.g. "pending").'),createdAt:I.string().datetime().describe("When the invitation was created."),expiresAt:I.string().datetime().describe("When the invitation expires.")}),BcA=I.string().min(1).describe("A user ID, or a URL-encoded email address, of the member."),j3A=I.object({organizationId:I.string().min(1).optional().describe("Organization to list members for. Auto-filled from CLI and SDK context when omitted.")}),_3A=I.object({members:I.array(ocA).describe("Members visible within the selected organization.")}),m3A=I.object({organizationId:I.string().min(1).optional().describe("Organization containing the member. Auto-filled from CLI and SDK context when omitted."),member:BcA.describe("User ID, or URL-encoded email address, of the member to update."),role:bo.describe("Role to assign.")}),x3A=I.object({member:ocA.describe("Updated organization member.")}),q3A=I.object({params:I.object({member:BcA.describe("User ID, or URL-encoded email address, of the member to remove.")}),query:I.object({organizationId:I.string().min(1).optional().describe("Organization containing the member. Auto-filled from CLI and SDK context when omitted.")})}).transform(({params:A,query:t})=>({...t,...A})),d3A=I.object({removedUserId:I.string().min(1).describe("User ID removed from the organization.")}),Uf=L({operationId:"members.list",description:"List members in an organization.",backend:"api",route:{method:"GET",path:"/members",tags:["Members"]},input:j3A,output:_3A,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"}]}}]}),Ff=L({operationId:"members.updateRole",description:"Update a member's organization role.",backend:"api",route:{method:"PATCH",path:"/members/{member}/role",tags:["Members"]},input:m3A,output:x3A,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"}}}]}),Lf=L({operationId:"members.remove",description:"Remove a member from an organization.",backend:"api",route:{method:"DELETE",path:"/members/{member}",tags:["Members"],inputStructure:"detailed"},input:q3A,output:d3A,pagination:"none",async:"sync"}),p3A=I.object({organizationId:I.string().min(1).optional().describe("Organization to invite into. Auto-filled from CLI and SDK context when omitted."),email:I.string().email().describe("Email address to invite."),role:bo.optional().default("member").describe('Role to grant on acceptance. Defaults to "member".')}),s3A=I.object({invitation:IcA.describe("The created pending invitation.")}),A7A=I.object({organizationId:I.string().min(1).optional().describe("Organization to list invitations for. Auto-filled from CLI and SDK context when omitted.")}),t7A=I.object({invitations:I.array(IcA).describe("Pending invitations visible within the selected organization.")}),g7A=I.object({params:I.object({invitationId:I.string().min(1).describe("ID of the invitation to revoke.")}),query:I.object({organizationId:I.string().min(1).optional().describe("Organization containing the invitation. Auto-filled from CLI and SDK context when omitted.")})}).transform(({params:A,query:t})=>({...t,...A})),n7A=I.object({revokedInvitationId:I.string().min(1).describe("ID of the revoked invitation.")}),Sf=L({operationId:"members.invite",description:"Invite a person to the organization by email.",backend:"api",route:{method:"POST",path:"/members/invitations",tags:["Members"],successStatus:201},input:p3A,output:s3A,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"}}}]}),lf=L({operationId:"members.listInvitations",description:"List pending invitations for an organization.",backend:"api",route:{method:"GET",path:"/members/invitations",tags:["Members"]},input:A7A,output:t7A,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"}]}}]}),Mf=L({operationId:"members.revokeInvitation",description:"Revoke a pending invitation.",backend:"api",route:{method:"DELETE",path:"/members/invitations/{invitationId}",tags:["Members"],inputStructure:"detailed"},input:g7A,output:n7A,pagination:"none",async:"sync"}),W1t={list:Uf.contract,updateRole:Ff.contract,remove:Lf.contract,invite:Sf.contract,listInvitations:lf.contract,revokeInvitation:Mf.contract}});var CcA,ccA,gN,EcA,nN,ecA=4194304,Yf,$f,i7A=(A)=>{let t=A.split(",").map((i)=>i.trim()).filter(Boolean),g=I.array(gN).safeParse(t);if(!g.success)throw Error("Kind filter must be a comma-separated list of note, runbook, or change.");return g.data},cy,kf,Gf,ycA,DcA,wcA,acA,rcA,bcA,NcA,ucA,UcA,FcA,LcA,ScA,Je,Te,Re,Pe,fe,Q7A;var Jf=D(()=>{TA();jA();CcA=["note","runbook"],ccA=["note","runbook","change"],gN=I.enum(ccA),EcA=I.enum(CcA),nN=I.string().min(1).max(512).refine((A)=>!A.startsWith("/"),{message:"Path must be relative without a leading slash."}).describe("Relative memory path, for example AGENTS.md or notes/architecture.md."),Yf=I.string().min(1).refine((A)=>new TextEncoder().encode(A).length<=ecA,{message:`Memory body must be at most ${ecA} bytes (4 MiB).`}).describe("Document body stored in project memory."),$f=I.string().regex(/^(\d+)(s|m|h|d)$/u,"Duration must use s, m, h, or d units, for example 7d or 30m.").describe("Relative time window, for example 7d or 30m."),cy=I.string().min(1).transform(i7A).describe("Comma-separated kinds, for example note,runbook."),kf=I.object({id:I.string().uuid(),projectId:I.string().uuid(),kind:gN,managed:I.boolean(),path:I.string().nullable(),title:I.string().nullable(),contentHash:I.string(),attrs:I.record(I.string(),I.unknown()),createdAt:I.string().datetime(),updatedAt:I.string().datetime()}),Gf=kf.extend({body:Yf}),ycA=I.object({projectId:I.string().uuid().optional().describe("Project that owns the document. Auto-filled from CLI and SDK context when omitted."),path:nN.describe("Relative path for the curated document."),body:Yf,kind:EcA.default("note").describe("Curated document kind. Only note and runbook may be written through the API."),title:I.string().max(500).optional().describe("Optional display title. Defaults to the path basename.")}),DcA=I.object({document:Gf}),wcA=I.object({projectId:I.string().uuid().optional().describe("Project that owns the document. Auto-filled from CLI and SDK context when omitted."),id:I.string().uuid().optional().describe("Document id."),path:nN.optional().describe("Relative curated path.")}).superRefine((A,t)=>{let g=A.id!==void 0,i=A.path!==void 0;if(g===i)t.addIssue({code:"custom",message:"Provide exactly one of id or path."})}),acA=I.object({document:Gf}),rcA=I.object({projectId:I.string().uuid().optional().describe("Project to list memory for. Auto-filled from CLI and SDK context when omitted."),kind:cy.optional(),since:$f.optional().describe("Only return documents updated within this window, for example 7d."),service:I.string().min(1).optional().describe("Filter to documents whose attrs.services contains this value."),pathPrefix:I.string().min(1).optional().describe("Filter to paths starting with this prefix."),managed:I.coerce.boolean().optional(),cursor:I.string().optional().describe("Cursor from a previous response's nextCursor to fetch the next page."),limit:I.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of documents to return per page.")}),bcA=I.object({documents:I.array(kf),nextCursor:I.string().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),NcA=I.object({documentId:I.string().uuid(),kind:gN,managed:I.boolean(),path:I.string().nullable(),title:I.string().nullable(),snippet:I.string(),score:I.number()}),ucA=I.object({calibrated:I.literal(!0),minScoreThreshold:I.number(),queryTerms:I.array(I.string()),message:I.string()}),UcA=I.object({projectId:I.string().uuid().optional().describe("Project to search memory for. Auto-filled from CLI and SDK context when omitted."),query:I.string().trim().min(1).max(500).describe("Natural-language search query."),kind:cy.optional(),since:$f.optional(),service:I.string().min(1).optional(),pathPrefix:I.string().min(1).optional(),managed:I.coerce.boolean().optional(),limit:I.coerce.number().int().min(1).max(50).default(10).describe("Maximum ranked search hits to return.")}),FcA=I.object({hits:I.array(NcA),emptyVerdict:ucA.nullable()}),LcA=I.object({projectId:I.string().uuid().optional().describe("Project that owns the document. Auto-filled from CLI and SDK context when omitted."),id:I.string().uuid().optional().describe("Document id."),path:nN.optional()}).superRefine((A,t)=>{let g=A.id!==void 0,i=A.path!==void 0;if(g===i)t.addIssue({code:"custom",message:"Provide exactly one of id or path."})}),ScA=I.void(),Je=L({operationId:"memory.put",description:"Create or replace a curated project memory document. Embeds on success.",backend:"api",route:{method:"PUT",path:"/memory",tags:["Memory"]},input:ycA,output:DcA,pagination:"none",async:"sync"}),Te=L({operationId:"memory.get",description:"Get one project memory document by id or path.",backend:"api",route:{method:"GET",path:"/memory/document",tags:["Memory"]},input:wcA,output:acA,pagination:"none",async:"sync"}),Re=L({operationId:"memory.list",description:"List project memory catalog rows without embedding search.",backend:"api",route:{method:"GET",path:"/memory",tags:["Memory"]},input:rcA,output:bcA,pagination:"cursor",async:"sync"}),Pe=L({operationId:"memory.search",description:"Hybrid semantic and keyword search over project memory documents.",backend:"api",route:{method:"POST",path:"/memory/search",tags:["Memory"]},input:UcA,output:FcA,pagination:"none",async:"sync"}),fe=L({operationId:"memory.delete",description:"Soft-delete a curated project memory document by id or path.",backend:"api",route:{method:"DELETE",path:"/memory/document",successStatus:204,tags:["Memory"]},input:LcA,output:ScA,pagination:"none",async:"sync"}),Q7A={put:Je.contract,get:Te.contract,list:Re.contract,search:Pe.contract,delete:fe.contract}});var lcA,McA,o7A,I7A,B7A,h7A,e7A,Ey,C7A,c7A,E7A,Tf,Rf,Pf,ff,m1t;var iN=D(()=>{TA();jA();lcA=I.enum(["processing","completed","aborted","error"]),McA=I.object({id:I.string().uuid(),threadId:I.string().uuid(),userMessageId:I.string().uuid().nullable(),assistantMessageId:I.string().uuid().nullable(),parentRunId:I.string().uuid().nullable(),workflowRunId:I.string().nullable(),status:lcA,source:I.enum(["app","api","mcp","slack","teams","linear","github","agent","cli","web","sdk","bitbucket","system"]),createdAt:I.string().datetime(),updatedAt:I.string().datetime(),completedAt:I.string().datetime().nullable()}),o7A=I.object({projectId:I.string().uuid().optional().describe("Project ID to list runs for. Auto-filled from CLI and SDK context when omitted."),limit:I.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of runs to return per page."),cursor:I.string().datetime().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),I7A=I.object({runs:I.array(McA),nextCursor:I.string().datetime().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),B7A=I.object({threadId:I.string().uuid().describe("Thread ID to list runs for."),limit:I.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of runs to return per page."),cursor:I.string().datetime().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),h7A=I.object({runs:I.array(McA),nextCursor:I.string().datetime().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),e7A=I.object({runId:I.string().uuid().describe("Run ID returned by a deferred operation.")}),Ey=I.object({completed:I.boolean().describe("Whether the run has reached a terminal status."),threadId:I.string().uuid().describe("Thread ID associated with the run."),runId:I.string().uuid().describe("Run ID for subsequent polling."),messageId:I.string().uuid().optional().describe("ID of the user message that triggered this run."),status:lcA.describe("Current run lifecycle status."),response:I.string().nullable().describe("Assistant response text when the run has completed.")}),C7A=Ey.describe("Current run state and, when complete, the assistant response."),c7A=I.object({runId:I.string().uuid().describe("Run ID of the in-flight run to request cancellation for.")}),E7A=I.object({success:I.literal(!0).describe("Always true when the cancellation request was accepted.")}),Tf=L({operationId:"runs.list",description:"List deferred runs within one project.",backend:"api",route:{method:"GET",path:"/runs",tags:["Runs"]},input:o7A,output:I7A,pagination:"cursor",async:"sync"}),Rf=L({operationId:"runs.listForThread",summary:"List Runs for a Thread",description:"List deferred runs for one thread.",backend:"api",route:{method:"GET",path:"/threads/{threadId}/runs",tags:["Runs"]},input:B7A,output:h7A,pagination:"cursor",async:"sync"}),Pf=L({operationId:"runs.get",description:"Get the current result for a deferred run by run ID.",backend:"api",route:{method:"GET",path:"/runs/{runId}",tags:["Runs"]},input:e7A,output:C7A,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}}]}),ff=L({operationId:"runs.cancel",description:"Request cancellation of an in-flight run. Idempotent and best-effort: returns success even when the run has already reached a terminal status.",backend:"api",route:{method:"POST",path:"/runs/{runId}/cancel",tags:["Runs"]},input:c7A,output:E7A,pagination:"none",async:"sync",examples:[{name:"cancel-processing-run",input:{runId:"33333333-3333-4333-8333-333333333333"},output:{success:!0}}]}),m1t={list:Tf.contract,listForThread:Rf.contract,get:Pf.contract,cancel:ff.contract}});var QN=(A,t,g)=>{let i=t?20000:1e4;if(A.length>i)g.addIssue({code:"too_big",maximum:i,type:"string",inclusive:!0,message:`Message cannot exceed ${i} characters`,origin:"string",path:["message"]})},oN=(A,t,g)=>{if(A&&!t)g.addIssue({code:"custom",message:"ambientServiceRun requires an automationId",path:["ambientServiceRun"]})};var YcA,yy,y7A,D7A,w7A,a7A,r7A,b7A,N7A,u7A,U7A,zf,F7A,L7A,S7A,l7A,M7A,Y7A,$7A,k7A,G7A,J7A,T7A,R7A,Of,vf,Zf,Wf,Vf,Xf,$cA,P7A,f7A,z7A,O7A,kcA,v7A,Z7A,W7A,V7A,X7A,H7A,WI="22222222-2222-4222-8222-222222222222",GcA="11111111-1111-4111-8111-111111111111",K7A="44444444-4444-4444-8444-444444444444",JcA="55555555-5555-4555-8555-555555555555",Hf,Kf,jf,_f,mf,tvt;var xf=D(()=>{TA();jA();iN();YcA=I.enum(["slack","teams","linear","github","app","mcp","agent","api","cli","web","sdk","bitbucket","system"]),yy=I.object({id:I.string().uuid(),projectId:I.string().uuid(),title:I.string().nullable(),status:I.enum(["regular","archived"]),source:YcA.nullable(),createdAt:I.string().datetime(),updatedAt:I.string().datetime()}),y7A=I.object({type:I.literal("message"),message:I.string()}),D7A=I.object({type:I.literal("reasoning"),reasoning:I.string(),status:I.enum(["in_progress","complete"]).optional()}),w7A=I.object({type:I.literal("tool_call"),name:I.string(),params:I.any().optional(),result:I.any().optional(),status:I.enum(["in_progress","success","error","unknown"]).optional(),toolCallId:I.string().optional(),durationMs:I.number().nonnegative().optional()}),a7A=I.object({type:I.literal("artifact"),name:I.enum(["timeseries","table","log_detail","integration_required","alert_card","issue_card","mdx"]),data:I.any(),toolCallId:I.string().optional()}),r7A=I.object({type:I.literal("fork"),sourceThreadId:I.string(),sourceMessageId:I.string(),sourceThreadTitle:I.string().nullable()}),b7A=I.object({type:I.literal("summary"),summary:I.string()}),N7A=I.object({type:I.literal("slack_context"),channelId:I.string(),isTruncated:I.boolean().optional(),messages:I.array(I.object({timestamp:I.string(),slackUserId:I.string().optional(),displayName:I.string(),text:I.string(),isBot:I.boolean(),files:I.array(I.object({name:I.string(),mimetype:I.string(),size:I.number().optional(),attachmentId:I.string().uuid().optional(),ingestionStatus:I.enum(["attached","unsupported","oversized","skipped","unavailable"]).optional()})).optional()}))}),u7A=I.object({type:I.literal("teams_context"),conversationId:I.string(),isTruncated:I.boolean().optional(),messages:I.array(I.object({activityId:I.string().optional(),displayName:I.string(),text:I.string(),isBot:I.boolean(),createdDateTime:I.string().optional()}))}),U7A=I.union([y7A,D7A,w7A,a7A,r7A,b7A,N7A,u7A]),zf=I.object({id:I.string().uuid(),role:I.enum(["user","assistant"]),content:I.array(U7A),source:YcA,createdAt:I.string().datetime()}),F7A=I.object({projectId:I.string().uuid().optional().describe("Project to list threads for. Auto-filled from CLI and SDK context when omitted."),limit:I.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of threads to return per page."),cursor:I.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page."),status:I.enum(["regular","archived"]).optional().describe("Filter by thread status. 'regular' returns active threads, 'archived' returns archived threads.")}),L7A=I.object({threads:I.array(yy).describe("The page of threads matching the query."),nextCursor:I.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),S7A=I.object({threadId:I.string().uuid().describe("Thread ID returned by threads.list or threads.create.")}),l7A=I.object({thread:yy.describe("The requested thread."),messages:I.array(zf).describe("Messages currently stored on the thread in chronological order.")}),M7A=I.object({projectId:I.string().uuid().optional().describe("Project to create the thread in. Auto-filled from CLI and SDK context when omitted."),message:I.string().min(1,"Message cannot be empty").describe("Initial user message that starts the thread."),wait:I.boolean().default(!0).describe("Whether the server should wait for the agent run before responding."),timeoutSeconds:I.coerce.number().int().min(1).max(20).default(20).describe("Maximum seconds to wait when wait is true before handing off to polling."),automationId:I.string().uuid().optional().describe("Internal automation context. Set by the Sazabi CLI when an automation script starts an agent run."),ambientServiceRun:I.literal(!0).optional().describe("Internal marker for scheduler-originated ambient service work. Honored only for system secret-key requests with matching automation context.")}).superRefine((A,t)=>{QN(A.message,A.automationId,t),oN(A.ambientServiceRun,A.automationId,t)}),Y7A=Ey.describe("Deferred run result for creating a thread."),$7A=I.object({threadId:I.string().uuid().describe("Thread ID whose current processing status should be returned.")}),k7A=I.object({status:I.enum(["idle","processing"]),lastRunStatus:I.enum(["error"]).nullable()}),G7A=I.object({threadId:I.string().uuid().describe("Thread ID whose active run should be stopped.")}),J7A=I.object({success:I.literal(!0).describe("Always true when the stop request was accepted.")}),T7A=I.object({threadId:I.string().uuid().describe("Thread ID of the thread to update."),status:I.enum(["regular","archived"]).describe("New status for the thread. 'archived' hides the thread from the sidebar.")}),R7A=I.object({thread:yy.describe("The updated thread.")}),Of=L({operationId:"threads.list",description:"List threads in a project, optionally filtered by status.",backend:"api",route:{method:"GET",path:"/threads",tags:["Threads"]},input:F7A,output:L7A,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}}]}),vf=L({operationId:"threads.get",description:"Get a thread and its messages.",backend:"api",route:{method:"GET",path:"/threads/{threadId}",tags:["Threads"]},input:S7A,output:l7A,pagination:"none",async:"sync"}),Zf=L({operationId:"threads.getStatus",description:"Get the current processing status for a thread.",backend:"api",route:{method:"GET",path:"/threads/{threadId}/status",tags:["Threads"]},input:$7A,output:k7A,pagination:"none",async:"sync",examples:[{name:"processing-thread",input:{threadId:"22222222-2222-4222-8222-222222222222"},output:{status:"processing",lastRunStatus:null}}]}),Wf=L({operationId:"threads.stop",description:"Stop a thread's in-flight run. Idempotent and best-effort: returns success even when the thread has no active run.",backend:"api",route:{method:"POST",path:"/threads/{threadId}/stop",tags:["Threads"]},input:G7A,output:J7A,pagination:"none",async:"sync",examples:[{name:"stop-processing-thread",input:{threadId:"22222222-2222-4222-8222-222222222222"},output:{success:!0}}]}),Vf=L({operationId:"threads.create",description:"Create a thread with an initial message and optionally wait for the agent response.",backend:"api",route:{method:"POST",path:"/threads",tags:["Threads"],successStatus:201},input:M7A,output:Y7A,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}}]}),Xf=L({operationId:"threads.update",description:"Update a thread's status.",backend:"api",route:{method:"PATCH",path:"/threads/{threadId}",tags:["Threads"]},input:T7A,output:R7A,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"}}}]}),$cA=I.enum(["private","organization"]),P7A=I.object({threadId:I.string().uuid().describe("Thread ID of the source thread to fork."),messageId:I.string().uuid().describe("Message ID in the source thread to fork from. The new thread copies messages up to and including this message.")}),f7A=I.object({thread:yy.describe("The newly created forked thread.")}),z7A=I.object({threadId:I.string().uuid().describe("Thread ID of the thread to update."),visibility:$cA.describe("New visibility. 'private' restricts the thread to its owner; 'organization' shares it with the organization.")}),O7A=I.object({thread:yy.describe("The updated thread."),visibility:$cA.describe("The thread's resulting visibility.")}),kcA=I.object({shareId:I.string().uuid().describe("Unique identifier for the snapshot."),threadId:I.string().uuid().describe("Thread the snapshot was taken from."),url:I.string().describe("Public read-only URL for the snapshot."),createdAt:I.string().datetime()}),v7A=I.object({threadId:I.string().uuid().describe("Thread ID to create a public read-only snapshot for.")}),Z7A=I.object({share:kcA.describe("The created share link.")}),W7A=I.object({threadId:I.string().uuid().describe("Thread ID the snapshot belongs to."),shareId:I.string().uuid().describe("Snapshot ID to revoke.")}),V7A=I.void(),X7A=I.object({threadId:I.string().uuid().describe("Thread ID to list public snapshots for.")}),H7A=I.object({shares:I.array(kcA).describe("Active share links for the thread.")}),Hf=L({operationId:"threads.fork",description:"Fork a thread from a specific message, creating a new thread that copies messages up to that point.",backend:"api",route:{method:"POST",path:"/threads/{threadId}/fork",tags:["Threads"],successStatus:201},input:P7A,output:f7A,pagination:"none",async:"sync",examples:[{name:"fork-from-message",input:{threadId:WI,messageId:K7A},output:{thread:{id:"66666666-6666-4666-8666-666666666666",projectId:GcA,title:"API returning 500s (fork)",status:"regular",source:"api",createdAt:"2026-01-01T00:20:00.000Z",updatedAt:"2026-01-01T00:20:00.000Z"}}}]}),Kf=L({operationId:"threads.setVisibility",description:"Set a thread's visibility to private or organization.",backend:"api",route:{method:"PATCH",path:"/threads/{threadId}/visibility",tags:["Threads"]},input:z7A,output:O7A,pagination:"none",async:"sync",examples:[{name:"make-private",input:{threadId:WI,visibility:"private"},output:{thread:{id:WI,projectId:GcA,title:"API returning 500s",status:"regular",source:"api",createdAt:"2026-01-01T00:00:00.000Z",updatedAt:"2026-01-01T00:30:00.000Z"},visibility:"private"}}]}),jf=L({operationId:"threads.createShareLink",description:"Create a public read-only share link for a thread's current messages.",backend:"api",route:{method:"POST",path:"/threads/{threadId}/share",tags:["Threads"],successStatus:201},input:v7A,output:Z7A,pagination:"none",async:"sync",examples:[{name:"create-share-link",input:{threadId:WI},output:{share:{shareId:JcA,threadId:WI,url:"https://app.sazabi.com/share/55555555-5555-4555-8555-555555555555",createdAt:"2026-01-01T00:40:00.000Z"}}}]}),_f=L({operationId:"threads.listShareLinks",description:"List active public share links for a thread.",backend:"api",route:{method:"GET",path:"/threads/{threadId}/share",tags:["Threads"]},input:X7A,output:H7A,pagination:"none",async:"sync",examples:[{name:"list-share-links",input:{threadId:WI},output:{shares:[{shareId:JcA,threadId:WI,url:"https://app.sazabi.com/share/55555555-5555-4555-8555-555555555555",createdAt:"2026-01-01T00:40:00.000Z"}]}}]}),mf=L({operationId:"threads.revokeShareLink",description:"Revoke a public share link for a thread.",backend:"api",route:{method:"DELETE",path:"/threads/{threadId}/share/{shareId}",successStatus:204,tags:["Threads"]},input:W7A,output:V7A,pagination:"none",async:"sync"}),tvt={list:Of.contract,get:vf.contract,getStatus:Zf.contract,stop:Wf.contract,create:Vf.contract,update:Xf.contract,fork:Hf.contract,setVisibility:Kf.contract,createShareLink:jf.contract,listShareLinks:_f.contract,revokeShareLink:mf.contract}});var j7A,_7A,m7A,x7A,TcA,RcA;var PcA=D(()=>{TA();jA();iN();xf();j7A=I.object({threadId:I.string().uuid().describe("Thread ID to list messages for."),limit:I.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of messages to return per page."),cursor:I.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),_7A=I.object({messages:I.array(zf),nextCursor:I.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),m7A=I.object({threadId:I.string().uuid().describe("Thread ID to append the message to."),message:I.string().min(1,"Message cannot be empty").describe("Message body to append to the thread."),wait:I.boolean().default(!0).describe("Whether the server should wait for the appended message run before responding."),timeoutSeconds:I.coerce.number().int().min(1).max(20).default(20).describe("Maximum seconds to wait when wait is true before handing off to polling."),automationId:I.string().uuid().optional().describe("Internal automation context. Set by the Sazabi CLI when an automation script starts an agent run."),ambientServiceRun:I.literal(!0).optional().describe("Internal marker for scheduler-originated ambient service work. Honored only for system secret-key requests with matching automation context.")}).superRefine((A,t)=>{QN(A.message,A.automationId,t),oN(A.ambientServiceRun,A.automationId,t)}),x7A=Ey.describe("Deferred run result for appending a message to an existing thread."),TcA=L({operationId:"messages.list",description:"List messages in a thread with cursor pagination.",backend:"api",route:{method:"GET",path:"/threads/{threadId}/messages",tags:["Messages"]},input:j7A,output:_7A,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}}]}),RcA=L({operationId:"messages.append",description:"Append a user message to an existing thread and trigger a deferred run.",backend:"api",route:{method:"POST",path:"/threads/{threadId}/messages",successStatus:201,tags:["Messages"]},input:m7A,output:x7A,pagination:"none",async:"deferred",examples:[{name:"append-processing",input:{threadId:"22222222-2222-4222-8222-222222222222",message:"Follow up on the intake backlog.",wait:!1,timeoutSeconds:20},output:{completed:!1,threadId:"22222222-2222-4222-8222-222222222222",runId:"33333333-3333-4333-8333-333333333333",status:"processing",response:null}}]})});var En,zcA,qf,ze,df,IN,No,OcA,fcA;var Dy=D(()=>{TA();En={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"},zcA=[En.IN_APP,En.SLACK,En.EMAIL,En.SMS],qf=[En.SLACK_CHANNEL,En.MICROSOFT_TEAMS_CHANNEL,En.INCIDENT_IO,En.PAGERDUTY,En.ROOTLY,En.WEBHOOK],ze=Object.values(En),df=[...ze,"victorops"],IN=I.enum(ze),No=I.enum(qf),OcA=[{channel:"in_app",name:"In-app",description:"Show notifications in your Sazabi notification feed.",scope:"personal",destinationManagement:"none",personalSettingsPath:"/settings/notifications"},{channel:"email",name:"Email",description:"Send notifications to your account email address.",scope:"personal",destinationManagement:"none",personalSettingsPath:"/settings/notifications"},{channel:"sms",name:"SMS",description:"Send notifications to your verified phone number.",scope:"personal",destinationManagement:"none",personalSettingsPath:"/settings/account?phone-number=add"},{channel:"slack",name:"Slack DMs",description:"Send personal notifications by Slack DM.",scope:"personal",destinationManagement:"none",personalSettingsPath:"/settings/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"}],fcA=new Set(OcA.map(({channel:A})=>A));if(fcA.size!==ze.length||ze.some((A)=>!fcA.has(A)))throw Error("Notification channel definitions must represent every channel")});var vcA,q7A=(A,t)=>A.value===t.value&&A.label===t.label&&A.scope===t.scope&&A.role===t.role&&A.defaultOff===t.defaultOff&&(A.defaultOffChannels??[]).join(",")===(t.defaultOffChannels??[]).join(",")&&A.email?.template===t.email?.template&&A.email?.ctaLabel===t.email?.ctaLabel&&(A.deliveryConditions??[]).join(",")===(t.deliveryConditions??[]).join(","),Jg=(A)=>{for(let t of Object.values(A)){let g=vcA.get(t.value);if(g&&!q7A(g,t))throw Error(`Notification type registered twice with conflicting definitions: ${t.value}`);if(t.role!==void 0&&t.scope!=="org")throw Error(`Notification type role restrictions require org scope: ${t.value}`);if(t.label.trim().length===0)throw Error(`Notification type needs a display label: ${t.value}`);if(t.email&&t.email.ctaLabel.trim().length===0)throw Error(`Notification email presentation needs a CTA label: ${t.value}`);if(t.defaultOff&&t.defaultOffChannels)throw Error(`Notification type declares both defaultOff and defaultOffChannels: ${t.value}`);vcA.set(t.value,t)}return A};var eQ=D(()=>{vcA=new Map});var ZcA;var WcA=D(()=>{eQ();ZcA=Jg({AUTOMATION_FINISHED:{value:"automation_finished",label:"Automation completed",scope:"project",defaultOff:!0},AUTOMATION_RUN_FAILED:{value:"automation_run_failed",label:"Automation run failed",scope:"project"}})});var BN;var pf=D(()=>{eQ();BN=Jg({BILLING_PLAN_UPGRADE_APPLIED:{value:"billing_plan_upgrade_applied",label:"Billing upgrade applied",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage billing"}},BILLING_PLAN_DOWNGRADE_SCHEDULED:{value:"billing_plan_downgrade_scheduled",label:"Billing downgrade scheduled",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage billing"}},BILLING_PLAN_DOWNGRADE_APPLIED:{value:"billing_plan_downgrade_applied",label:"Billing downgrade applied",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage billing"}},BILLING_CREDIT_BALANCE_LOW:{value:"billing_credit_balance_low",label:"Billing credits low",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage credits"}},BILLING_CREDIT_BALANCE_DEPLETED:{value:"billing_credit_balance_depleted",label:"Billing credits depleted",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage credits"}},BILLING_AUTO_TOP_UP_SETTINGS_CHANGED:{value:"billing_auto_top_up_settings_changed",label:"Billing auto top-up changed",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage auto top-up"}},BILLING_AUTO_TOP_UP_FAILED:{value:"billing_auto_top_up_failed",label:"Billing auto top-up failed",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage payment method"}},BILLING_INVOICE_PAID:{value:"billing_invoice_paid",label:"Billing invoice paid",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"View invoice"}},BILLING_INVOICE_PAYMENT_FAILED:{value:"billing_invoice_payment_failed",label:"Billing invoice payment failed",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Update payment method"}},BILLING_SUBSCRIPTION_CANCELLATION_SCHEDULED:{value:"billing_subscription_cancellation_scheduled",label:"Billing cancellation scheduled",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage subscription"}},BILLING_SUBSCRIPTION_CANCELED:{value:"billing_subscription_canceled",label:"Billing subscription canceled",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"View billing"}},BILLING_PAYMENT_METHOD_EXPIRING:{value:"billing_payment_method_expiring",label:"Billing payment method expiring",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Update payment method"}},BILLING_PAYMENT_METHOD_CHANGED:{value:"billing_payment_method_changed",label:"Billing payment method changed",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Review payment method"}},BILLING_NEGATIVE_BALANCE_COLLECTED:{value:"billing_negative_balance_collected",label:"Billing outstanding balance charged",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"View billing"}},BILLING_NEGATIVE_BALANCE_COLLECTION_FAILED:{value:"billing_negative_balance_collection_failed",label:"Billing outstanding balance charge failed",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage payment method"}}})});var VcA;var XcA=D(()=>{eQ();VcA=Jg({INTEGRATION_CONNECTED:{value:"integration_connected",label:"Integration connected",scope:"org",defaultOff:!0},INTEGRATION_DISCONNECTED:{value:"integration_disconnected",label:"Integration disconnected",scope:"org"}})});var HcA;var KcA=D(()=>{eQ();HcA=Jg({ISSUE_TRIGGERED:{value:"issue_triggered",label:"Issue triggered",scope:"project",deliveryConditions:["component","severity"]},ISSUE_RESOLVED:{value:"issue_resolved",label:"Issue resolved",scope:"project",defaultOffChannels:["email"],deliveryConditions:["component","severity"]},ISSUE_IGNORED:{value:"issue_ignored",label:"Issue ignored",scope:"project",defaultOffChannels:["email"],deliveryConditions:["component","severity"]}})});var jcA;var _cA=D(()=>{eQ();jcA=Jg({PROJECT_CREATED:{value:"project_created",label:"Project created",scope:"org",defaultOff:!0},PROJECT_DELETED:{value:"project_deleted",label:"Project deleted",scope:"org",defaultOff:!0},MEMBER_INVITED:{value:"member_invited",label:"Member invited",scope:"org",defaultOff:!0},USER_REMOVED:{value:"user_removed",label:"Member removed",scope:"org",defaultOff:!0},MCP_CONNECTOR_ADDED:{value:"mcp_connector_added",label:"MCP connector added",scope:"org",defaultOff:!0},MCP_CONNECTOR_REMOVED:{value:"mcp_connector_removed",label:"MCP connector removed",scope:"org",defaultOff:!0},SECRET_KEY_CREATED:{value:"secret_key_created",label:"Secret key created",scope:"org",defaultOff:!0},SECRET_KEY_DELETED:{value:"secret_key_deleted",label:"Secret key deleted",scope:"org",defaultOff:!0}})});var mcA;var xcA=D(()=>{eQ();mcA=Jg({SANDBOX_CREATED:{value:"sandbox_created",label:"Sandbox connected",scope:"project",defaultOff:!0},SANDBOX_DELETED:{value:"sandbox_deleted",label:"Sandbox disconnected",scope:"project",defaultOff:!0},LOG_SOURCE_CONNECTED:{value:"log_source_connected",label:"Log source connected",scope:"project",defaultOff:!0},LOG_SOURCE_DISCONNECTED:{value:"log_source_disconnected",label:"Log source disconnected",scope:"project"},GITHUB_CONNECTED:{value:"github_connected",label:"GitHub connected",scope:"project",defaultOff:!0},GITHUB_DISCONNECTED:{value:"github_disconnected",label:"GitHub disconnected",scope:"project"},CODE_REPO_CONNECTED:{value:"code_repo_connected",label:"Code repository connected",scope:"project",defaultOff:!0},CODE_REPO_DISCONNECTED:{value:"code_repo_disconnected",label:"Code repository disconnected",scope:"project"},PUBLIC_KEY_DEACTIVATED:{value:"public_key_deactivated",label:"Public key deactivated",scope:"project"}})});var qcA;var dcA=D(()=>{eQ();qcA=Jg({SECURITY_ALERT:{value:"security_alert",label:"Security alert",scope:"org",role:"admin"}})});var sf,Mt,p7A,Az=(A)=>{let t=p7A.get(A)?.label;if(t)return t;let g=A.replace(/_/g," ").trim();return g?g.charAt(0).toUpperCase()+g.slice(1):A};var wy=D(()=>{WcA();pf();pf();XcA();KcA();_cA();xcA();dcA();eQ();sf={...qcA,...jcA,...VcA,...ZcA,...HcA,...mcA,...BN},Mt=Object.fromEntries(Object.entries(sf).map(([A,t])=>[A,t.value])),p7A=new Map(Object.values(sf).map((A)=>[A.value,A]))});var hN,scA,zvt,Pi,Ovt;var VI=D(()=>{wy();Dy();Dy();hN=Object.values(Mt),scA=[Mt.BILLING_PLAN_UPGRADE_APPLIED,Mt.BILLING_PLAN_DOWNGRADE_SCHEDULED,Mt.BILLING_PLAN_DOWNGRADE_APPLIED,Mt.BILLING_CREDIT_BALANCE_LOW,Mt.BILLING_CREDIT_BALANCE_DEPLETED,Mt.BILLING_AUTO_TOP_UP_SETTINGS_CHANGED,Mt.BILLING_AUTO_TOP_UP_FAILED,Mt.BILLING_INVOICE_PAID,Mt.BILLING_NEGATIVE_BALANCE_COLLECTED,Mt.BILLING_NEGATIVE_BALANCE_COLLECTION_FAILED,Mt.BILLING_INVOICE_PAYMENT_FAILED,Mt.BILLING_SUBSCRIPTION_CANCELLATION_SCHEDULED,Mt.BILLING_SUBSCRIPTION_CANCELED,Mt.BILLING_PAYMENT_METHOD_EXPIRING,Mt.BILLING_PAYMENT_METHOD_CHANGED],zvt=new Set(scA),Pi=[Mt.ISSUE_TRIGGERED,Mt.ISSUE_RESOLVED,Mt.ISSUE_IGNORED,Mt.AUTOMATION_RUN_FAILED],Ovt=new Set(Pi)});var ay,AEA,tEA=(A)=>typeof A==="string"&&(A in AEA)?AEA[A]:A,AxA;var gEA=D(()=>{Dy();TA();VI();ay=I.enum(hN),AEA={data_source_connected:"log_source_connected",data_source_disconnected:"log_source_disconnected"},AxA=I.preprocess(tEA,ay)});var txA;var nEA=D(()=>{wy();VI();txA=Pi.map((A)=>({notificationType:A,label:Az(A)}))});var iEA=D(()=>{wy();VI()});var QEA=D(()=>{Dy();wy();VI();gEA();nEA();iEA()});var oEA=()=>{};var IEA=D(()=>{VI()});var BEA=D(()=>{VI()});var tz=D(()=>{oEA();IEA();BEA();QEA()});var QxA,oxA,IxA,BxA,hxA,exA,CxA,gz,A4t;var hEA=D(()=>{tz();TA();jA();QxA=I.enum(["ready","missing","degraded","unavailable"]),oxA=I.object({id:I.string(),label:I.string(),status:I.enum(["active","inactive","degraded"]),statusLabel:I.string()}),IxA=I.object({channel:IN,name:I.string(),description:I.string(),scope:I.enum(["personal","project"]),enabled:I.boolean().nullable(),preferenceId:I.string().nullable(),prerequisite:I.object({status:QxA,statusLabel:I.string(),message:I.string()}),action:I.object({label:I.string(),href:I.string()}).nullable(),destinations:I.array(oxA),destinationManagement:I.enum(["none","slack_channels","teams_channels","integration_connections","webhook_endpoints"]),canCreateDestinations:I.boolean(),supportedNotificationTypes:I.array(ay)}),BxA=I.object({channel:No,enabled:I.boolean(),preferenceId:I.string().nullable()}),hxA=I.object({channel:No,notificationType:ay,enabled:I.boolean(),preferenceId:I.string()}),exA=I.object({projectId:I.string().uuid().optional().describe("Project to inspect. Auto-filled from CLI and SDK context when omitted.")}),CxA=I.object({channelCards:I.array(IxA).length(10),channels:I.array(BxA),notificationTypePreferences:I.array(hxA),issueNotificationMinSeverity:I.enum(["low","medium","high","critical"])}),gz=L({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.",backend:"api",route:{method:"GET",path:"/notification-channels",tags:["Notification channels"]},input:exA,output:CxA,pagination:"none",async:"sync"}),A4t={getProject:gz.contract}});var eEA,iz,CEA,Qz,Q4t,o4t,oz,Iz=(A,t)=>{if((A.componentIds?.length||A.componentId)&&"componentIds"in A.condition&&A.condition.componentIds?.length)t.addIssue({code:"custom",path:["condition","componentIds"],message:"Use componentIds instead of legacy condition.componentIds."});if(A.componentIds?.length&&A.componentId)t.addIssue({code:"custom",path:["componentId"],message:"Use componentIds instead of componentId."})},I4t,cEA,nz,Bz,ry,EEA,cxA,ExA,yxA,DxA,wxA,axA,rxA,bxA,NxA,hz,ez,Cz,cz,Ez,B4t;var yEA=D(()=>{tz();TA();jA();eEA=I.enum(["low","medium","high","critical"]),iz=I.object({severities:I.array(eEA).min(1).optional()}).strict(),CEA=I.object({componentIds:I.array(I.string().uuid()).min(1).optional(),severities:I.array(eEA).min(1).optional()}).strict(),Qz=I.object({channel:No,destinationKey:I.string().min(1)}),Q4t=I.object({destinations:I.array(Qz).min(1),notificationTypes:I.array(I.enum(Pi)).min(1),componentIds:I.array(I.string().uuid()).min(1).optional().describe("Stable component registry IDs matched by this rule."),includeDescendants:I.boolean().default(!1).describe("Whether the rule also matches descendant components."),condition:iz}),o4t=I.object({destinations:I.array(Qz).min(1),notificationTypes:I.array(I.enum(Pi)).min(1),condition:CEA}),oz=I.object({destinations:I.array(Qz).min(1),notificationTypes:I.array(I.enum(Pi)).min(1),componentIds:I.array(I.string().uuid()).min(1).optional().describe("Stable component registry IDs matched by this rule."),componentId:I.string().uuid().optional().describe("Deprecated single-component compatibility input."),includeDescendants:I.boolean().default(!1).describe("Whether the rule also matches descendant components."),condition:I.union([iz,CEA])}),I4t=oz.superRefine(Iz),cEA=I.object({id:I.string(),channel:No,destinationKey:I.string(),displayName:I.string()}),nz=I.object({id:I.string().uuid(),label:I.string(),lifecycle:I.enum(["active","retired","merged"])}),Bz=I.object({id:I.string().uuid(),projectId:I.string().uuid(),notificationTypes:I.array(I.enum(Pi)),destinations:I.array(cEA),condition:iz,component:nz.nullable(),componentId:I.string().uuid().nullable(),includeDescendants:I.boolean(),suspendedAt:I.string().datetime().nullable(),suspensionReason:I.string().nullable(),components:I.array(nz),createdAt:I.string().datetime(),updatedAt:I.string().datetime()}),ry=I.object({projectId:I.string().uuid().optional().describe("Project whose notification delivery rules are being managed.")}),EEA=I.string().uuid().describe("Logical notification delivery rule ID."),cxA=ry,ExA=I.object({rules:I.array(Bz)}),yxA=I.object({destinations:I.array(cEA),notificationTypes:I.array(I.object({notificationType:I.enum(Pi),label:I.string(),conditions:I.array(I.enum(["component","severity"]))})),components:I.array(nz)}),DxA=ry.extend(oz.shape).superRefine(Iz),wxA=Bz,axA=ry.extend({...oz.shape,ruleId:EEA}).superRefine(Iz),rxA=Bz,bxA=ry.extend({ruleId:EEA}),NxA=I.object({removed:I.boolean()}),hz=L({operationId:"notificationDeliveryRules.list",description:"List the positive delivery rules for a project.",backend:"api",route:{method:"GET",path:"/notification-delivery-rules",tags:["Notification delivery rules"]},input:cxA,output:ExA,pagination:"none",async:"sync"}),ez=L({operationId:"notificationDeliveryRules.options",description:"List available destinations, events, and conditions for project delivery rules.",backend:"api",route:{method:"GET",path:"/notification-delivery-rules/options",tags:["Notification delivery rules"]},input:ry,output:yxA,pagination:"none",async:"sync"}),Cz=L({operationId:"notificationDeliveryRules.create",description:"Create a positive project notification delivery rule.",backend:"api",route:{method:"POST",path:"/notification-delivery-rules",tags:["Notification delivery rules"]},input:DxA,output:wxA,pagination:"none",async:"sync"}),cz=L({operationId:"notificationDeliveryRules.update",description:"Replace a positive delivery rule atomically.",backend:"api",route:{method:"PUT",path:"/notification-delivery-rules/{ruleId}",tags:["Notification delivery rules"]},input:axA,output:rxA,pagination:"none",async:"sync"}),Ez=L({operationId:"notificationDeliveryRules.delete",description:"Delete a positive delivery rule without deleting its reusable destinations.",backend:"api",route:{method:"DELETE",path:"/notification-delivery-rules/{ruleId}",tags:["Notification delivery rules"]},input:bxA,output:NxA,pagination:"none",async:"sync"}),B4t={list:hz.contract,options:ez.contract,create:Cz.contract,update:cz.contract,delete:Ez.contract}});var yz,uxA,UxA,FxA,LxA,SxA,lxA,Dz,MxA,YxA,wz,$xA,kxA,az,GxA,JxA,rz,TxA,RxA,bz,c4t;var DEA=D(()=>{TA();jA();yz=I.enum(["verify-email","accept-invite","create-organization","billing","configure-project","connect-github-account","install-github-app","configure-code-search","install-slack-app","configure-slack-notifications","trigger-issue","confirm-issue","finish"]),uxA=I.enum(["needs-onboarding","blocked","ready"]),UxA=I.enum(["incomplete","complete","skipped"]),FxA=I.object({invitationId:I.string(),organizationId:I.string(),organizationName:I.string(),organizationSlug:I.string(),organizationImageUrl:I.string().nullable(),inviterName:I.string().nullable()}),LxA=I.object({gate:uxA,canonicalStep:yz.nullable(),organizationId:I.string().nullable(),projectId:I.string().nullable(),completionByStep:I.record(yz,UxA),githubSkipped:I.boolean(),githubAppSkipped:I.boolean(),slackSkipped:I.boolean(),sampleIssueId:I.string().nullable(),actorRole:I.enum(["admin","member"]).nullable(),requiredStep:I.union([yz,I.literal("select-organization")]).nullable(),isCompleted:I.boolean(),onboardingRecommendationsThreadId:I.string().nullable(),hasOrganizations:I.boolean(),hasPaidBillingSubscription:I.boolean(),billingStepEnabled:I.boolean(),pendingInvitations:I.array(FxA)}),SxA=I.object({projectId:I.string().uuid().optional().describe("Project whose onboarding state to bind (sample-issue attempt and project-scoped facts). Auto-filled from CLI and SDK context when omitted.")}),lxA=I.object({onboarding:LxA}),Dz=L({operationId:"onboarding.getState",description:"Read onboarding progress for the authenticated user.",backend:"api",route:{method:"GET",path:"/onboarding/state",tags:["Onboarding"]},input:SxA,output:lxA,pagination:"none",async:"sync"}),MxA=I.object({integration:I.enum(["github","slack"]).describe("Integration onboarding step to skip.")}),YxA=I.object({skipped:I.literal(!0)}),wz=L({operationId:"onboarding.skipIntegration",description:"Skip a GitHub or Slack integration step during onboarding.",backend:"api",route:{method:"POST",path:"/onboarding/skip-integration",tags:["Onboarding"]},input:MxA,output:YxA,pagination:"none",async:"sync"}),$xA=I.object({}),kxA=I.object({skipped:I.literal(!0)}),az=L({operationId:"onboarding.skipGithubAppInstallation",summary:"Skip GitHub App Installation",description:"Skip GitHub App installation during onboarding.",backend:"api",route:{method:"POST",path:"/onboarding/skip-github-app",tags:["Onboarding"]},input:$xA,output:kxA,pagination:"none",async:"sync"}),GxA=I.object({}),JxA=I.object({skipped:I.literal(!0)}),rz=L({operationId:"onboarding.skipSampleIssue",summary:"Skip Test Issue",description:"Skip the optional test issue during onboarding.",backend:"api",route:{method:"POST",path:"/onboarding/skip-sample-issue",tags:["Onboarding"]},input:GxA,output:JxA,pagination:"none",async:"sync"}),TxA=I.object({projectId:I.string().uuid().describe("Project that completed onboarding.")}),RxA=I.object({completed:I.boolean()}),bz=L({operationId:"onboarding.finish",description:"Mark onboarding complete when all prerequisites are satisfied.",backend:"api",route:{method:"POST",path:"/onboarding/finish",tags:["Onboarding"]},input:TxA,output:RxA,pagination:"none",async:"sync"}),c4t={getState:Dz.contract,skipIntegration:wz.contract,skipGithubAppInstallation:az.contract,skipSampleIssue:rz.contract,finish:bz.contract}});var eN,PxA,fxA,zxA,OxA,vxA,ZxA,WxA,VxA,XxA,HxA,Nz,uz,Uz,Fz,a4t;var wEA=D(()=>{TA();jA();tN();eN=I.object({id:I.string().min(1),name:I.string(),slug:I.string(),logo:I.string().nullable().optional()}),PxA=eN.extend({role:bo.optional()}),fxA=I.object({}),zxA=I.object({organizations:I.array(PxA).describe("Organizations available to the current credential.")}),OxA=I.object({organizationId:I.string().min(1).describe("Organization ID to fetch.")}),vxA=I.object({organization:eN}),ZxA=I.object({organizationId:I.string().min(1).describe("Organization ID to update. SDK and CLI callers can auto-fill this before dispatch."),name:I.string().trim().min(1).max(100).describe("New organization name.")}),WxA=I.object({organization:eN.describe("Updated organization.")}),VxA=I.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(/^[\p{L}\p{N} _-]+$/u,"Name can only contain letters, numbers, spaces, hyphens, and underscores"),XxA=I.object({name:VxA.describe("Organization display name.")}),HxA=I.object({organization:eN}),Nz=L({operationId:"organizations.create",description:"Create an organization for the authenticated user.",backend:"api",route:{method:"POST",path:"/organizations",tags:["Organizations"],successStatus:201},input:XxA,output:HxA,pagination:"none",async:"sync"}),uz=L({operationId:"organizations.list",description:"List organizations available to the current credential.",backend:"api",route:{method:"GET",path:"/organizations",tags:["Organizations"]},input:fxA,output:zxA,pagination:"none",async:"sync"}),Uz=L({operationId:"organizations.get",description:"Get one organization by ID.",backend:"api",route:{method:"GET",path:"/organizations/{organizationId}",tags:["Organizations"]},input:OxA,output:vxA,pagination:"none",async:"sync"}),Fz=L({operationId:"organizations.update",description:"Update one organization.",backend:"api",route:{method:"PATCH",path:"/organizations/{organizationId}",tags:["Organizations"]},input:ZxA,output:WxA,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}}}]}),a4t={list:uz.contract,get:Uz.contract,create:Nz.contract,update:Fz.contract}});var Oe,by,aEA,rEA,bEA,NEA,uEA,UEA,FEA,CN,cN,EN,LEA,SEA,yN,lEA,MEA,DN,KxA;var Lz=D(()=>{TA();jA();Oe=I.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"]),by=I.object({id:I.string().uuid(),organizationId:I.string().min(1),name:I.string(),region:Oe}),aEA=I.object({organizationId:I.string().min(1).optional().describe("Organization to list projects for. Auto-filled from CLI and SDK context when omitted.")}),rEA=I.object({projects:I.array(by).describe("Projects visible within the selected organization.")}),bEA=I.object({projectId:I.string().uuid().describe("Project ID to fetch.")}),NEA=I.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(/^[\p{L}\p{N} _-]+$/u,"Name can only contain letters, numbers, spaces, hyphens, and underscores"),uEA=I.object({organizationId:I.string().min(1).optional().describe("Organization to create the project under. Auto-filled from CLI and SDK context when omitted."),name:NEA.describe("Project name."),region:Oe.optional().default("us-west-2").describe("AWS region where the new project should be created.")}),UEA=I.object({project:by}),FEA=I.object({project:by}),CN=L({operationId:"projects.list",description:"List projects in an organization.",backend:"api",route:{method:"GET",path:"/projects",tags:["Projects"]},input:aEA,output:rEA,pagination:"none",async:"sync"}),cN=L({operationId:"projects.get",description:"Get one project by ID.",backend:"api",route:{method:"GET",path:"/projects/{projectId}",tags:["Projects"]},input:bEA,output:FEA,pagination:"none",async:"sync"}),EN=L({operationId:"projects.create",description:"Create one project in an organization.",backend:"api",route:{method:"POST",path:"/projects",successStatus:201,tags:["Projects"]},input:uEA,output:UEA,pagination:"none",async:"sync"}),LEA=I.object({projectId:I.string().uuid().describe("Project ID to update."),name:NEA.optional().describe("New project name.")}),SEA=I.object({project:by}),yN=L({operationId:"projects.update",description:"Update (rename) one project by ID. User credentials require the `settings:write` organization permission (admin or owner role).",backend:"api",route:{method:"PATCH",path:"/projects/{projectId}",tags:["Projects"]},input:LEA,output:SEA,pagination:"none",async:"sync"}),lEA=I.object({projectId:I.string().uuid().describe("Project ID to delete.")}),MEA=I.void(),DN=L({operationId:"projects.delete",description:"Delete one project by ID. User credentials require the `settings:write` organization permission (admin or owner role).",backend:"api",route:{method:"DELETE",path:"/projects/{projectId}",successStatus:204,tags:["Projects"]},input:lEA,output:MEA,pagination:"none",async:"sync"}),KxA={list:CN.contract,get:cN.contract,create:EN.contract,update:yN.contract,delete:DN.contract}});var YEA,jxA,_xA,mxA,xxA,qxA,Sz,L4t;var $EA=D(()=>{TA();jA();YEA=I.enum(["open","merged","closed"]),jxA=I.enum(["review_required","approved","changes_requested"]),_xA=I.enum(["passing","failing","pending"]),mxA=I.object({id:I.string().uuid(),projectId:I.string().uuid(),repositoryFullName:I.string(),pullRequestId:I.string().describe("Provider-native pull request identifier (GitHub PR number or Bitbucket PR id), serialized as a string."),githubPullRequestId:I.number().int().describe("Deprecated: use pullRequestId. Numeric form of the provider-native pull request identifier; kept for backward compatibility."),title:I.string().nullable(),url:I.string().nullable(),status:YEA.nullable(),reviewState:jxA.nullable(),checksState:_xA.nullable(),requestedByUserId:I.string().nullable(),authorLogin:I.string().nullable().describe("Forge login that authored the pull request (often the Sazabi app identity)."),githubAuthorLogin:I.string().nullable().describe("Deprecated: use authorLogin. Kept for backward compatibility."),threadId:I.string().uuid().nullable(),runId:I.string().uuid().nullable(),createdAt:I.string().datetime(),mergedAt:I.string().datetime().nullable(),closedAt:I.string().datetime().nullable()}),xxA=I.object({projectId:I.string().uuid().optional().describe("Project to list pull requests for. Auto-filled from CLI and SDK context when omitted."),limit:I.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of pull requests to return per page."),cursor:I.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page."),status:YEA.optional().describe("Filter by pull request status (open, merged, or closed)."),repositoryFullName:I.string().trim().optional().describe("Filter by repository full name, for example owner/repo. Case-insensitive."),requestedByUserId:I.string().trim().optional().describe("Filter by the Sazabi user who requested the pull request. Pass 'me' to filter to the authenticated user.")}),qxA=I.object({pullRequests:I.array(mxA),nextCursor:I.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),Sz=L({operationId:"pullRequests.list",description:"List pull requests that Sazabi opened, optionally filtered by status, repository, and requesting user.",backend:"api",route:{method:"GET",path:"/pull-requests",tags:["Pull Requests"]},input:xxA,output:qxA,pagination:"cursor",async:"sync"}),L4t={list:Sz.contract}});var kEA,GEA,JEA,TEA,REA,Ny;var lz=D(()=>{TA();jA();kEA=I.enum(["log_source","mcp_connector","sandbox_cli","integration"]),GEA=I.enum(["connected","recommended"]),JEA=I.object({kind:kEA.describe("What the recommendation targets: a log source, MCP connector, sandbox CLI, or integration."),targetId:I.string().describe("Exact catalog id for the kind (log source type, MCP provider id, sandbox CLI preset type, or integration provider id)."),status:GEA.describe("Resolved live against current connections: connected (already set up) or recommended (suggested, not yet connected)."),roiScore:I.number().int().min(0).max(100).describe("Intrinsic ROI score, 0–100 — a normalized blend of how valuable, how easy to connect, and how proven the item is. A pure function of the item; computed live on read, never stored."),priority:I.number().int().min(1).describe("1-based rank within this list, sorted by roiScore (best first). Items are already returned in priority order; the field lets consumers recover the rank without trusting array position.")}),TEA=I.object({projectId:I.string().uuid().optional().describe("Project to list recommendations for. Auto-filled from CLI and SDK context when omitted.")}),REA=I.object({recommendations:I.array(JEA).describe("The project's configuration recommendations, deduped by (kind, targetId), with status resolved live and each item's ROI score. Returned in priority order (highest roiScore first).")}),Ny=L({operationId:"recommendations.list",description:"List a project's configuration recommendations (data sources, MCP connectors, sandbox CLIs, and integrations) with each item's live connection status.",backend:"api",route:{method:"GET",path:"/recommendations",tags:["Recommendations"]},input:TEA,output:REA,pagination:"none",async:"sync"})});var PEA,Mz,fEA,zEA,OEA,vEA,ZEA,WEA,uy,Uy,Fy;var Yz=D(()=>{TA();jA();PEA=I.enum(["github","bitbucket"]),Mz=I.object({id:I.string().uuid().describe("Repository row id — stable across access sources; use it as the path id for repos.remove."),accessSourceId:I.string().uuid().describe("Access source granting this view of the repository (GitHub App installation, personal connection, or integration). Pass to repos.add to link the repository through this source."),provider:PEA.describe("Forge hosting the repository."),owner:I.string().describe("Repository owner (user or organization)."),name:I.string().describe("Repository name without the owner."),fullName:I.string().describe("Full name in owner/name form."),defaultBranch:I.string().nullable().describe("Default branch, when the forge reports one."),isPrivate:I.boolean().describe("Whether the repository is private."),linked:I.boolean().describe("Whether the repository is already linked to the project.")}),fEA=I.object({projectId:I.string().uuid().optional().describe("Project to list repositories for. Auto-filled from CLI and SDK context when omitted.")}),zEA=I.object({repos:I.array(Mz).describe("Every repository available to the project's organization (from GitHub App installations, the caller's personal forge connections, and integrations), with `linked` marking the ones already linked to the project.")}),OEA=I.object({projectId:I.string().uuid().optional().describe("Project to link the repositories to. Auto-filled from CLI and SDK context when omitted."),accessSourceIds:I.array(I.string().uuid()).min(1).describe("Access source ids (from repos.list) to link. Select only one access source per repository.")}),vEA=I.object({repos:I.array(Mz).describe("The now-linked repositories.")}),ZEA=I.object({id:I.string().uuid().describe("Repository row id (from repos.list) to unlink."),projectId:I.string().uuid().optional().describe("Project to unlink the repository from. Auto-filled from CLI and SDK context when omitted.")}),WEA=I.void(),uy=L({operationId:"repos.list",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.",backend:"api",route:{method:"GET",path:"/repos",tags:["Repos"]},input:fEA,output:zEA,pagination:"none",async:"sync"}),Uy=L({operationId:"repos.add",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.",backend:"api",route:{method:"POST",path:"/repos",tags:["Repos"]},input:OEA,output:vEA,pagination:"none",async:"sync"}),Fy=L({operationId:"repos.remove",description:"Unlink a repository from a project by repository row id.",backend:"api",route:{method:"DELETE",path:"/repos/{id}",successStatus:204,tags:["Repos"]},input:ZEA,output:WEA,pagination:"none",async:"sync"})});var VEA,dxA,XEA,wN,HEA,KEA,jEA,_EA,ve,$z,mEA,xEA,Ze,qEA,dEA,We,pEA,sEA,Ve,pxA;var kz=D(()=>{TA();jA();VEA=I.object({type:I.string().describe("Preset type identifier."),label:I.string().describe("Human-readable display name."),executableNames:I.array(I.string()).describe("CLI binary names installed by this preset."),envVarKeys:I.array(I.string()).describe("Environment variables required for authentication."),setupSkill:I.string().nullable().describe("Markdown setup skill for AI agents. Null when no skill is available.")}),dxA=I.object({}),XEA=I.object({types:I.array(VEA)}),wN=L({operationId:"sandboxPresets.listTypes",description:"List all supported sandbox CLI types with their environment variable requirements and setup skills.",backend:"api",route:{method:"GET",path:"/sandbox-presets/types",tags:["Sandbox Presets"]},input:dxA,output:XEA,pagination:"none",async:"sync"}),HEA=I.enum(["github_app","bitbucket_integration","personal_access_token","stored_credentials"]),KEA=I.object({presetType:I.string().describe("Preset type identifier."),credentialSource:HEA.describe("Authoritative credential source for the preset."),isSystemManaged:I.boolean().describe("Whether the connection follows an integration lifecycle."),fallbackConfigured:I.boolean().describe("Whether user-provided fallback credentials are stored for this preset."),envVarKeys:I.array(I.string()).describe("Stored environment variable names. Secret values are omitted.")}),jEA=I.object({projectId:I.string().uuid().optional().describe("Project to inspect. Required for organization-scoped keys; auto-filled from a project-scoped key when omitted.")}),_EA=I.object({connections:I.array(KEA)}),ve=L({operationId:"sandboxPresets.listConnections",description:"List a project's stored and integration-backed sandbox CLI connections without returning secret values.",backend:"api",route:{method:"GET",path:"/sandbox-presets/connections",tags:["Sandbox Presets"]},input:jEA,output:_EA,pagination:"none",async:"sync"}),$z=I.object({key:I.string().min(1).max(256).regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"Environment variable keys must match /^[A-Za-z_][A-Za-z0-9_]*$/.").describe("Environment variable name (e.g. KUBECONFIG_CONTENTS)."),value:I.string().max(10240).describe("Secret value. Encrypted at rest; never returned by any API response.")}),mEA=I.object({projectId:I.string().uuid().optional().describe("Project to configure. Required for organization-scoped keys; auto-filled from a project-scoped key when omitted."),presetType:I.string().min(1).describe("Preset type identifier (e.g. kubectl, aws, github)."),environmentVariables:I.array($z).max(100).describe("Full set of env vars for this preset. Replaces any previously stored values for the preset.")}),xEA=I.object({projectId:I.string().uuid().describe("Project the preset was written to."),presetType:I.string().describe("Preset type that was upserted."),envVarKeys:I.array(I.string()).describe("Env var key names now stored for this preset. Values are never returned.")}),Ze=L({operationId:"sandboxPresets.upsertPreset",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.",backend:"api",route:{method:"POST",path:"/sandbox-presets/config",successStatus:200,tags:["Sandbox Presets"]},input:mEA,output:xEA,pagination:"none",async:"sync"}),qEA=I.object({projectId:I.string().uuid().optional().describe("Project to update. Required for organization-scoped keys; auto-filled from a project-scoped key when omitted."),presetType:I.string().min(1).describe("Preset type identifier.")}),dEA=I.object({projectId:I.string().uuid().describe("Project the CLI connection belonged to."),presetType:I.string().describe("Preset type that was disconnected."),deleted:I.boolean().describe("Whether a stored CLI connection was deleted.")}),We=L({operationId:"sandboxPresets.deletePreset",summary:"Disconnect CLI",description:"Delete a project's stored CLI connection. Integration-managed access remains available until its owning integration is disconnected.",backend:"api",route:{method:"DELETE",path:"/sandbox-presets/config/{presetType}",tags:["Sandbox Presets"]},input:qEA,output:dEA,pagination:"none",async:"sync"}),pEA=I.object({projectId:I.string().uuid().optional().describe("Project to test from. Required for organization-scoped keys; auto-filled from a project-scoped key when omitted."),presetType:I.string().min(1).describe("Preset type identifier."),environmentVariables:I.array($z).max(100).describe("Unsaved credentials to validate in a readonly sandbox.")}),sEA=I.object({status:I.enum(["success","failed"]),message:I.string().nullable(),stdout:I.string().describe("Truncated command output with submitted credentials redacted."),stderr:I.string().describe("Truncated command errors with submitted credentials redacted.")}),Ve=L({operationId:"sandboxPresets.testPreset",summary:"Test CLI connection",description:"Validate unsaved CLI credentials in a read-only ephemeral sandbox without persisting them.",backend:"api",route:{method:"POST",path:"/sandbox-presets/test",tags:["Sandbox Presets"]},input:pEA,output:sEA,pagination:"none",async:"sync"}),pxA={deletePreset:We.contract,listConnections:ve.contract,listTypes:wN.contract,testPreset:Ve.contract,upsertPreset:Ze.contract}});var aN,AyA=1048576,Gz,tyA,Jz,sxA,AqA,tqA,gqA,nqA,iqA,QqA,oqA,IqA,BqA,Tz,Rz,Pz,fz,zz,z4t;var gyA=D(()=>{TA();jA();aN=I.string().min(1).max(64).regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/,"Name must start with a letter or digit and contain only letters, digits, underscores, and hyphens (max 64 characters).").describe("Script name. Must be unique within the project among non-deleted scripts."),Gz=I.string().min(1).refine((A)=>new TextEncoder().encode(A).length<=AyA,{message:`Script content must be at most ${AyA} bytes (1 MiB).`}).describe("Bash script body materialized as /home/sazabi/scripts/<name>.sh in the sandbox."),tyA=I.object({id:I.string().uuid(),projectId:I.string().uuid(),name:I.string(),description:I.string().nullable(),contentHash:I.string().describe("sha256 hex digest of the script content."),createdAt:I.string().datetime(),updatedAt:I.string().datetime()}),Jz=tyA.extend({content:Gz}),sxA=I.object({projectId:I.string().uuid().optional().describe("Project to list scripts for. Auto-filled from CLI and SDK context when omitted."),search:I.string().optional().describe("Case-insensitive partial match on script name."),cursor:I.string().optional().describe("Cursor from a previous response's nextCursor to fetch the next page."),limit:I.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of scripts to return per page.")}),AqA=I.object({scripts:I.array(tyA),nextCursor:I.string().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),tqA=I.object({name:aN.describe("Script name to fetch."),projectId:I.string().uuid().optional().describe("Project that owns the script. Auto-filled from CLI and SDK context when omitted.")}),gqA=I.object({script:Jz}),nqA=I.object({projectId:I.string().uuid().optional().describe("Project that owns the script. Auto-filled from CLI and SDK context when omitted."),name:aN.describe("Script name. Must be unique within the project among non-deleted scripts."),content:Gz,description:I.string().max(500).nullable().optional().describe("Optional human-readable description.")}),iqA=I.object({script:Jz}),QqA=I.object({name:aN.describe("Script to update."),projectId:I.string().uuid().optional().describe("Project that owns the script. Auto-filled from CLI and SDK context when omitted."),content:Gz.optional().describe("New script body. Omit to leave content unchanged."),description:I.string().max(500).nullable().optional().describe("New description, or null to clear it. Omit to leave unchanged.")}),oqA=I.object({script:Jz}),IqA=I.object({name:aN.describe("Script to delete."),projectId:I.string().uuid().optional().describe("Project that owns the script. Auto-filled from CLI and SDK context when omitted.")}),BqA=I.void(),Tz=L({operationId:"scripts.list",description:"List durable bash scripts stored for a project.",backend:"api",route:{method:"GET",path:"/scripts",tags:["Scripts"]},input:sxA,output:AqA,pagination:"cursor",async:"sync"}),Rz=L({operationId:"scripts.get",description:"Get a single project script by name, including its body.",backend:"api",route:{method:"GET",path:"/scripts/{name}",tags:["Scripts"]},input:tqA,output:gqA,pagination:"none",async:"sync"}),Pz=L({operationId:"scripts.create",description:"Create a durable bash script for a project.",backend:"api",route:{method:"POST",path:"/scripts",successStatus:201,tags:["Scripts"]},input:nqA,output:iqA,pagination:"none",async:"sync"}),fz=L({operationId:"scripts.update",description:"Update a project script's body and/or description.",backend:"api",route:{method:"PATCH",path:"/scripts/{name}",tags:["Scripts"]},input:QqA,output:oqA,pagination:"none",async:"sync"}),zz=L({operationId:"scripts.delete",description:"Soft-delete a project script by name.",backend:"api",route:{method:"DELETE",path:"/scripts/{name}",successStatus:204,tags:["Scripts"]},input:IqA,output:BqA,pagination:"none",async:"sync"}),z4t={list:Tz.contract,get:Rz.contract,create:Pz.contract,update:fz.contract,delete:zz.contract}});var Oz,nyA,iyA,QyA,oyA,Xe,He,hqA;var vz=D(()=>{TA();jA();Oz=I.object({projectId:I.string().uuid().optional().describe("Project to search within. Auto-filled from CLI and SDK context when omitted."),query:I.string().trim().min(1,"Query must be at least 1 character").max(500,"Query must be at most 500 characters"),limit:I.coerce.number().min(1).max(100).default(20).describe("Maximum number of search results to return."),page:I.coerce.number().min(1).default(1).describe("One-based page number.")}),nyA=Oz.extend({status:I.enum(["regular","archived"]).optional().describe("Optional thread status filter.")}),iyA=Oz.extend({threadId:I.string().uuid().optional().describe("Optional thread restriction for message search."),role:I.enum(["user","assistant"]).optional().describe("Optional message role filter.")}),QyA=I.object({threads:I.array(I.object({id:I.string().uuid(),projectId:I.string().uuid().optional(),title:I.string(),status:I.enum(["regular","archived"]),labels:I.array(I.string()),createdAt:I.string().datetime(),updatedAt:I.string().datetime(),highlights:I.array(I.string()),score:I.number().optional()})),pagination:I.object({page:I.number(),limit:I.number(),totalResults:I.number(),totalPages:I.number()}).describe("Page-based pagination metadata for the current search result.")}),oyA=I.object({messages:I.array(I.object({id:I.string().uuid(),threadId:I.string().uuid(),threadTitle:I.string(),role:I.enum(["user","assistant"]),content:I.string(),createdAt:I.string().datetime(),updatedAt:I.string().datetime(),highlights:I.array(I.string()),score:I.number().optional()})),pagination:I.object({page:I.number(),limit:I.number(),totalResults:I.number(),totalPages:I.number()}).describe("Page-based pagination metadata for the current search result.")}),Xe=L({operationId:"search.threads",description:"Search threads within one project.",backend:"api",route:{method:"GET",path:"/search/threads",tags:["Search"]},input:nyA,output:QyA,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}}}]}),He=L({operationId:"search.messages",description:"Search messages within one project.",backend:"api",route:{method:"GET",path:"/search/messages",tags:["Search"]},input:iyA,output:oyA,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}}}]}),hqA={threads:Xe.contract,messages:He.contract}});var IyA;var ByA=D(()=>{IyA=["onboarding","setup"]});var hyA,eyA,CyA,cyA,Ly;var Zz=D(()=>{ByA();TA();jA();hyA=I.enum(IyA),eyA=I.object({id:I.string().describe("Unique task identifier (e.g. install_github_app)."),label:I.string().describe("Short human-readable task name."),description:I.string().describe("Explanation of what needs to be completed to satisfy this task."),instructions:I.string().describe("Step-by-step instructions for completing this task."),completed:I.boolean().describe("Whether the task has been completed."),completedAt:I.string().datetime().nullable().describe("ISO 8601 timestamp of when the task was completed, or null."),category:hyA.describe("Task category: onboarding (core setup steps) or setup (additional configuration).")}),CyA=I.object({projectId:I.string().uuid().optional().describe("Project to list tasks for. Auto-filled from CLI and SDK context when omitted.")}),cyA=I.object({tasks:I.array(eyA).describe("All onboarding and setup tasks with their current completion status.")}),Ly=L({operationId:"tasks.list",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.",backend:"api",route:{method:"GET",path:"/tasks",tags:["Tasks"]},input:CyA,output:cyA,pagination:"none",async:"sync"})});var eqA,CqA,XI,cqA,EqA,yqA,DqA,wqA,aqA,rqA,bqA,NqA,uqA,UqA,FqA,LqA,SqA,Wz,Vz,Xz,Hz,Kz,jz,_z,x4t;var EyA=D(()=>{TA();jA();eqA=I.object({id:I.string().uuid().describe("Team ID."),name:I.string().describe("Team name, unique among the org's active teams."),description:I.string().nullable().describe("Optional team description."),createdAt:I.string().datetime().describe("When the team was created."),memberCount:I.number().int().nonnegative().describe("Number of active members in the team.")}),CqA=I.object({userId:I.string().min(1).describe("User ID of the team member."),name:I.string().nullable().describe("Display name for the member, when available."),email:I.string().email().describe("Email address for the member."),addedAt:I.string().datetime().describe("When the member was added to the team.")}),XI=I.string().min(1).optional().describe("Organization to operate on. Auto-filled from CLI and SDK context when omitted."),cqA=I.object({organizationId:XI}),EqA=I.object({teams:I.array(eqA).describe("Active teams in the organization.")}),yqA=I.object({organizationId:XI,name:I.string().trim().min(1).describe("Team name."),description:I.string().trim().min(1).optional().describe("Optional team description.")}),DqA=I.object({id:I.string().uuid().describe("ID of the created team.")}),wqA=I.object({organizationId:XI,teamId:I.string().uuid().describe("Team to update."),name:I.string().trim().min(1).optional().describe("New team name."),description:I.string().trim().min(1).nullable().optional().describe("New team description; null clears it.")}),aqA=I.object({id:I.string().uuid().describe("ID of the updated team.")}),rqA=I.object({params:I.object({teamId:I.string().uuid().describe("Team to delete.")}),query:I.object({organizationId:XI})}).transform(({params:A,query:t})=>({...t,...A})),bqA=I.object({success:I.literal(!0).describe("The team and its memberships were removed.")}),NqA=I.object({organizationId:XI,teamId:I.string().uuid().describe("Team to add the member to."),userId:I.string().min(1).describe("User ID of an active organization member to add.")}),uqA=I.object({id:I.string().uuid().describe("ID of the team membership.")}),UqA=I.object({params:I.object({teamId:I.string().uuid().describe("Team to remove the member from."),userId:I.string().min(1).describe("User ID of the member to remove.")}),query:I.object({organizationId:XI})}).transform(({params:A,query:t})=>({...t,...A})),FqA=I.object({success:I.literal(!0).describe("The membership was removed.")}),LqA=I.object({organizationId:XI,teamId:I.string().uuid().describe("Team to list members for.")}),SqA=I.object({members:I.array(CqA).describe("Active members of the team.")}),Wz=L({operationId:"teams.list",description:"List teams in an organization.",backend:"api",route:{method:"GET",path:"/teams",tags:["Teams"]},input:cqA,output:EqA,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}]}}]}),Vz=L({operationId:"teams.create",description:"Create a team in an organization.",backend:"api",route:{method:"POST",path:"/teams",tags:["Teams"],successStatus:201},input:yqA,output:DqA,pagination:"none",async:"sync"}),Xz=L({operationId:"teams.update",description:"Rename a team or update its description.",backend:"api",route:{method:"PATCH",path:"/teams/{teamId}",tags:["Teams"]},input:wqA,output:aqA,pagination:"none",async:"sync"}),Hz=L({operationId:"teams.delete",description:"Delete a team, its memberships, and its component-ownership assignments.",backend:"api",route:{method:"DELETE",path:"/teams/{teamId}",tags:["Teams"],inputStructure:"detailed"},input:rqA,output:bqA,pagination:"none",async:"sync"}),Kz=L({operationId:"teams.addMember",description:"Add an active organization member to a team.",backend:"api",route:{method:"POST",path:"/teams/{teamId}/members",tags:["Teams"],successStatus:201},input:NqA,output:uqA,pagination:"none",async:"sync"}),jz=L({operationId:"teams.removeMember",description:"Remove a member from a team.",backend:"api",route:{method:"DELETE",path:"/teams/{teamId}/members/{userId}",tags:["Teams"],inputStructure:"detailed"},input:UqA,output:FqA,pagination:"none",async:"sync"}),_z=L({operationId:"teams.listMembers",description:"List a team's active members.",backend:"api",route:{method:"GET",path:"/teams/{teamId}/members",tags:["Teams"]},input:LqA,output:SqA,pagination:"none",async:"sync"}),x4t={list:Wz.contract,create:Vz.contract,update:Xz.contract,delete:Hz.contract,addMember:Kz.contract,removeMember:jz.contract,listMembers:_z.contract}});var lqA,MqA,YqA,mz,$qA,kqA,xz,GqA,JqA,qz,s4t;var yyA=D(()=>{TA();jA();lqA=I.object({kind:I.enum(["user","workspace"]),name:I.string().optional(),email:I.string().optional()}),MqA=I.object({container:I.string().min(1).describe("The container to create the work item in: its id, short key (e.g. a Linear team key like ENG), or display name."),title:I.string().min(1),bodyMarkdown:I.string().optional(),state:I.string().optional(),itemType:I.string().optional(),organizationId:I.string().min(1).optional().describe("Optional organization ID to scope the request to. User credentials must belong to it; a secret key may only reference its own organization. Defaults to the credential's active organization."),clientRequestId:I.string().min(1).optional().describe("Optional caller-supplied idempotency key. When provided, retrying the same logical create with the same clientRequestId reuses the original result instead of creating a duplicate external work item.")}).strict(),YqA=I.object({identifier:I.string(),title:I.string(),url:I.string(),state:I.string(),attribution:lqA.optional(),reused:I.boolean()}),mz=L({operationId:"work-items.create",description:"Create a work item (e.g. a Linear issue) in a connected issue tracker, attributing the write to the requesting user.",backend:"api",route:{method:"POST",path:"/work-items",tags:["Work Items"],successStatus:201},input:MqA,output:YqA,pagination:"none",async:"sync"}),$qA=I.object({itemId:I.string().min(1).describe("The work item to comment on."),bodyMarkdown:I.string().min(1),organizationId:I.string().min(1).optional().describe("Optional organization ID to scope the request to. User credentials must belong to it; a secret key may only reference its own organization. Defaults to the credential's active organization.")}).strict(),kqA=I.object({identifier:I.string(),url:I.string()}),xz=L({operationId:"work-items.comment",description:"Add a comment to an existing work item.",backend:"api",route:{method:"POST",path:"/work-items/{itemId}/comment",tags:["Work Items"]},input:$qA,output:kqA,pagination:"none",async:"sync"}),GqA=I.object({itemId:I.string().min(1).describe("The work item to transition."),state:I.string().min(1).describe("The target workflow state."),organizationId:I.string().min(1).optional().describe("Optional organization ID to scope the request to. User credentials must belong to it; a secret key may only reference its own organization. Defaults to the credential's active organization.")}).strict(),JqA=I.object({identifier:I.string(),title:I.string(),url:I.string(),state:I.string(),changed:I.boolean()}),qz=L({operationId:"work-items.transition",description:"Move a work item to a target workflow state.",backend:"api",route:{method:"POST",path:"/work-items/{itemId}/transition",tags:["Work Items"]},input:GqA,output:JqA,pagination:"none",async:"sync"}),s4t={create:mz.contract,comment:xz.contract,transition:qz.contract}});var dz;var DyA=D(()=>{zW();XW();gY();BY();cV();WY();HY();dV();ja();$_();Nk();Nf();tN();hcA();Jf();PcA();hEA();yEA();DEA();wEA();Lz();$EA();lz();Yz();iN();kz();gyA();vz();Zz();EyA();xf();yyA();dz={me:uf.contract,automations:{list:eY.contract,get:CY.contract,create:cY.contract,update:EY.contract,enable:yY.contract,disable:DY.contract,runs:{list:wY.contract,get:aY.contract,logs:rY.contract}},logs:{query:dB.contract,schema:pB.contract,volume:sB.contract,patterns:Ah.contract,nativeQuery:th.contract},logSources:{listProviders:Va.contract,list:xB.contract,create:qB.contract,get:Xa.contract,update:Ha.contract,delete:Ka.contract},logStreams:{list:Ek.contract,create:yk.contract,get:Dk.contract,update:wk.contract,delete:ak.contract,reassign:rk.contract},connectedAccounts:{beginConnect:iY.contract,getConnectAttempt:QY.contract,list:oY.contract,disconnect:IY.contract},integrations:{listProviders:KW.contract,listConnections:jW.contract,getConnection:_W.contract,createConnection:mW.contract,beginConnect:xW.contract,getConnectAttempt:qW.contract,disconnectConnection:dW.contract,updateConnectionCredentials:pW.contract,getOrganizationExternalIdentityJitPolicy:tV.contract,updateOrganizationExternalIdentityJitPolicy:gV.contract,getConnectionExternalIdentityJitPolicy:nV.contract,updateConnectionExternalIdentityJitPolicy:iV.contract,getSlackConfiguration:oV.contract,updateSlackConfiguration:IV.contract,listSlackChannelProjectMappings:hV.contract,setSlackChannelProjectMapping:eV.contract,deleteSlackChannelProjectMapping:CV.contract},notificationChannels:{getProject:gz.contract},notificationDeliveryRules:{list:hz.contract,options:ez.contract,create:Cz.contract,update:cz.contract,delete:Ez.contract},mcpConnectors:{listProviders:AN.contract,list:Ne.contract,get:ue.contract,details:Ue.contract,search:Fe.contract,describe:Le.contract,call:Se.contract,create:le.contract,update:Me.contract,disconnect:Ye.contract,setReadOnly:$e.contract,beginOAuthInstall:ke.contract,getOAuthInstallAttempt:Ge.contract},sandboxPresets:{deletePreset:We.contract,listConnections:ve.contract,listTypes:wN.contract,testPreset:Ve.contract,upsertPreset:Ze.contract},scripts:{list:Tz.contract,get:Rz.contract,create:Pz.contract,update:fz.contract,delete:zz.contract},logMatchExpressions:{list:_Y.contract,get:mY.contract,create:xY.contract,update:qY.contract,disable:dY.contract},memory:{put:Je.contract,get:Te.contract,list:Re.contract,search:Pe.contract,delete:fe.contract},onboarding:{getState:Dz.contract,skipIntegration:wz.contract,skipGithubAppInstallation:az.contract,skipSampleIssue:rz.contract,finish:bz.contract},organizations:{list:uz.contract,get:Uz.contract,create:Nz.contract,update:Fz.contract},members:{list:Uf.contract,updateRole:Ff.contract,remove:Lf.contract,invite:Sf.contract,listInvitations:lf.contract,revokeInvitation:Mf.contract},teams:{list:Wz.contract,create:Vz.contract,update:Xz.contract,delete:Hz.contract,addMember:Kz.contract,removeMember:jz.contract,listMembers:_z.contract},publicKeys:{list:XB.contract,get:HB.contract,ensureLogForwarding:KB.contract,update:jB.contract,deactivate:_B.contract},secretKeys:{list:Ta.contract,get:Ra.contract,create:Pa.contract,update:fa.contract,delete:za.contract},projects:{list:CN.contract,get:cN.contract,create:EN.contract,update:yN.contract,delete:DN.contract},search:{threads:Xe.contract,messages:He.contract},messages:{list:TcA.contract,append:RcA.contract},threads:{list:Of.contract,get:vf.contract,getStatus:Zf.contract,stop:Wf.contract,create:Vf.contract,update:Xf.contract,fork:Hf.contract,setVisibility:Kf.contract,createShareLink:jf.contract,listShareLinks:_f.contract,revokeShareLink:mf.contract},runs:{list:Tf.contract,listForThread:Rf.contract,get:Pf.contract,cancel:ff.contract},pullRequests:{list:Sz.contract},issues:{count:Ua.contract,create:VB.contract,list:Na.contract,search:ua.contract,get:Fa.contract,resolve:La.contract,ignore:Sa.contract,reopen:la.contract,reassignAndReopen:Ma.contract,mute:Ya.contract,unmute:$a.contract},workItems:{create:mz.contract,comment:xz.contract,transition:qz.contract},billing:{getSummary:NY.contract,getUsage:uY.contract,listTransactions:UY.contract,getAutoTopUp:SY.contract,updateAutoTopUp:lY.contract,purchaseCredits:MY.contract,listPlans:YY.contract,previewPlanChange:$Y.contract,previewSubscriptionCancellation:PY.contract,scheduleSubscriptionCancellation:fY.contract,resumeSubscriptionCancellation:zY.contract,changePlan:kY.contract,createCheckoutSession:GY.contract,getCheckoutSessionStatus:JY.contract,createPortalSession:TY.contract,getPaymentMethod:RY.contract},tasks:{list:Ly.contract},recommendations:{list:Ny.contract},repos:{list:uy.contract,add:Uy.contract,remove:Fy.contract},components:{list:pw.contract,get:sw.contract,register:ZB.contract,deregister:Aa.contract,rename:ta.contract,assignTeam:ga.contract,retirementPreview:na.contract,retire:ia.contract,restorationPreview:Qa.contract,restore:oa.contract,mergePreview:ca.contract,merge:Ea.contract,relationships:{list:Ia.contract,preview:Ba.contract,add:ha.contract,remove:ea.contract},incidents:{list:ya.contract},timeline:Da.contract}}});var HI=D(()=>{lZ();gY();BY();DyA();WY();HY();ja();Nk();Nf();Jf();Lz();lz();Yz();kz();vz();Zz()});var TqA="https://api.sazabi.com",RqA="x-sazabi-client-source",ayA=(A)=>{return{streamRun:async(t)=>{return wyA({options:A,path:`/runs/${encodeURIComponent(t.runId)}/stream`,cursor:t.cursor,signal:t.signal})},streamThread:async(t)=>{return wyA({options:A,path:`/threads/${encodeURIComponent(t.threadId)}/stream`,cursor:t.cursor,signal:t.signal})}}},wyA=async(A)=>{let t=A.options.fetch??globalThis.fetch;if(!t)throw Error("Fetch transport is not available in this runtime.");let g=await A.options.credentialProvider.getToken(),i=PqA(A.options.apiBaseUrl,A.path,A.cursor);return zqA({url:i,token:g,clientSource:A.options.clientSource,initialCursor:A.cursor,signal:A.signal,fetch:t})},PqA=(A,t,g)=>{let i=fqA(A??TqA),n=new URL(`${i}${t}`);if(g)n.searchParams.set(WM,g);return n.toString()},fqA=(A)=>{let t=A.replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`},zqA=async(A)=>{let t=[],g=[],i=!1,n=!1,Q,o=A.initialCursor,B=new AbortController,h=(a)=>{if(i)return;i=!0,Q=a;while(g.length>0)g.shift()?.({value:void 0,done:!0})},e=(a)=>{let u=g.shift();if(u){u({value:a,done:!1});return}t.push(a)},C=(a)=>{if(a.event===XM){let F=VqA(a.data);if(F!==void 0)o=F;return}if(a.data===HM){n=!0,B.abort(),h();return}let u=XqA(a.data);if(u)e(u)},c=()=>{n=!0,B.abort(),h()};if(A.signal)if(A.signal.aborted)n=!0,B.abort();else A.signal.addEventListener("abort",c,{once:!0});let E={[Symbol.asyncIterator](){return E},get cursor(){return o},next:async()=>{if(t.length>0)return{value:t.shift(),done:!1};if(i){if(Q)throw Q;return{value:void 0,done:!0}}return new Promise((a)=>{g.push(a)}).then((a)=>{if(a.done&&Q)throw Q;return a})},return:async()=>{return n=!0,B.abort(),h(),{value:void 0,done:!0}},throw:async(a)=>{throw n=!0,B.abort(),h(a instanceof Error?a:Error(String(a))),a},close:async()=>{n=!0,B.abort(),h()}};if(n)return h(),E;let y=await A.fetch(A.url,{method:VM,headers:OqA(A.token,A.clientSource),signal:B.signal});if(await vqA(y))h();else ZqA(y,C).then(()=>h()).catch((a)=>{if(KqA(a)||n||A.signal?.aborted){h();return}h(jqA(a))});return E},OqA=(A,t)=>{return{accept:"text/event-stream",authorization:`Bearer ${A}`,...t?{[RqA]:t}:{}}},vqA=async(A)=>{if(A.status===204)return!0;if(A.ok&&A.body)return!1;let t=await HqA(A);if(A.status===401)throw Error("Authentication failed. Check your credential.");if(A.status===403)throw Error(`Forbidden (403): ${t||"Credential may not have access to this resource"}`);if(A.status===404)throw Error(`Not found (404): ${t||"Run or thread not found"}`);if(A.status===400)throw Error(`Invalid stream cursor (400): ${t||"The provided cursor was rejected"}`);if(A.status>=400&&A.status<500&&A.status!==429)throw Error(`Client error (${A.status}): ${t}`);if(!A.body)throw Error("Agent stream response did not include a body.");throw Error(A.status===429?`Rate limited (429): ${t}`:`Server error (${A.status}): ${t}`)},ZqA=async(A,t)=>{let g=A.body?.getReader();if(!g)throw Error("Agent stream response did not include a body.");let i=new TextDecoder,n="",Q=WqA(t);try{while(!0){let o=await g.read();if(o.done)break;n+=i.decode(o.value,{stream:!0});let B=n.split(/\r\n|\r|\n/);n=B.pop()??"";for(let h of B)Q.line(h)}if(n+=i.decode(),n)for(let o of n.split(/\r\n|\r|\n/))Q.line(o);Q.flush()}finally{g.releaseLock()}},WqA=(A)=>{let t="message",g=[],i=()=>{t="message",g=[]},n=()=>{if(g.length===0){i();return}A({event:t,data:g.join(`
|
|
8707
|
+
`)}],evidenceHints:["force.com / my.salesforce.com URLs, SALESFORCE_* or SFDC_* environment variables, or sf/sfdx CLI usage","jsforce, simple-salesforce, or @salesforce packages","README/runbooks naming Salesforce as the CRM or system of record"],helpText:"Query Salesforce data and metadata, and run Apex invocable actions and Flows exposed by a hosted MCP server. Coming soon — a Salesforce admin registers an External Client App in your org and Sazabi provisions its credentials, so it isn't self-serve connectable yet."})});var eeA;var CeA=D(()=>{eA();eeA=V({id:"secureframe",label:"Secureframe",iconKey:"secureframe",defaultServerUrl:"https://mcp.secureframe.com",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"secureframe",callbackPathSegment:"secureframe",authorizationUrl:"https://mcp.secureframe.com/oauth/authorize",tokenUrl:"https://mcp.secureframe.com/oauth/token",resourceUrl:"https://mcp.secureframe.com",dynamicClientRegistration:{registrationEndpoint:"https://mcp.secureframe.com/register",tokenEndpointAuthMethod:"none"}},getAvailableScopes:async()=>[{value:"mcp",label:"MCP Access",description:"Query and manage Secureframe compliance data, controls, tests, vendors, risks, and framework requirements."}],scopesUserSelectable:!1,regions:[{label:"United States (US)",serverUrl:"https://mcp.secureframe.com"},{label:"United Kingdom (UK)",serverUrl:"https://mcp-uk.secureframe.com",authorizationUrl:"https://mcp-uk.secureframe.com/oauth/authorize",tokenUrl:"https://mcp-uk.secureframe.com/oauth/token",resourceUrl:"https://mcp-uk.secureframe.com",dynamicClientRegistration:{registrationEndpoint:"https://mcp-uk.secureframe.com/register",tokenEndpointAuthMethod:"none"}}],capabilityOverrides:{allowWriteTools:!0},evidenceHints:["secureframe.com URLs, SECUREFRAME_API_KEY / SECUREFRAME_API_SECRET environment variables","SOC 2, ISO 27001, HIPAA, PCI DSS, GDPR, or NIST compliance frameworks and controls","README/docs or compliance runbooks naming Secureframe for automated compliance and continuous monitoring"],helpText:"Query and manage Secureframe compliance data, controls, automated tests, vendors, risks, and framework requirements. Choose the US or UK region when connecting.",skill:"secureframe",setupSkill:"secureframe-setup"})});var ceA;var EeA=D(()=>{eA();ceA=V({id:"sentry",label:"Sentry",iconKey:"sentry",defaultServerUrl:"https://mcp.sentry.dev/mcp",serverUrlPathSuffixMaxSegments:2,transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"sentry",callbackPathSegment:"sentry",authorizationUrl:"https://mcp.sentry.dev/oauth/authorize",tokenUrl:"https://mcp.sentry.dev/oauth/token",useServerUrlAsResource:!0,dynamicClientRegistration:{registrationEndpoint:"https://mcp.sentry.dev/oauth/register",tokenEndpointAuthMethod:"none"}},scopesUserSelectable:!1,getAvailableScopes:async()=>[{value:"org:read"},{value:"project:write"},{value:"team:write"},{value:"event:write"}],getUrlConfiguration:async()=>({docsUrl:"https://mcp.sentry.dev/",instructions:"Copy the hosted MCP server URL below. Optional: to scope this connection to one organization or project, copy a path-scoped URL from the Sentry MCP page (e.g. .../mcp/your-org).",defaultServerUrl:"https://mcp.sentry.dev/mcp",optional:!0}),capabilityOverrides:{allowWriteTools:!0},evidenceHints:["@sentry packages, sentry.properties, SENTRY_* environment variables, or sentry-cli usage","Sentry.init calls, release/deploy automation, or Sentry alert docs","README/docs naming Sentry as the error tracking provider"],helpText:"Browse Sentry organizations, teams, projects, and events."})});var yeA;var DeA=D(()=>{Jt();eA();yeA=V({id:"signoz",label:"SigNoz",iconKey:"signoz",defaultServerUrl:"https://mcp.us.signoz.cloud/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!0},evidenceHints:["SigNoz config, SIGNOZ_* environment variables, or signoz.io links","OpenTelemetry Collector exporting to SigNoz, or a signoz docker-compose / self-hosted deployment","README/docs naming SigNoz for metrics, logs, traces, alerts, or dashboards"],helpText:"Query SigNoz metrics, logs, traces, alerts, and dashboards to investigate production issues.",setupGroups:[{id:"instance",title:"Find your SigNoz instance",description:"Point Sazabi at the SigNoz instance whose telemetry you want to query.",body:"For SigNoz Cloud, use the regional MCP endpoint for your account, such as `https://mcp.us.signoz.cloud/mcp` (replace the region as needed). For self-hosted SigNoz, use your instance's MCP endpoint and set the SigNoz base URL below so the server knows which instance to target.",fieldKeys:["signozUrl"]},{id:"api-key",title:"Create an API key",description:"Create or copy the SigNoz API key Sazabi will send to SigNoz's MCP endpoint.",body:"In SigNoz, go to **Settings > API Keys** and create or copy an API key. Alert, dashboard, and notification-channel tools require an admin-level key. Paste it below.",fieldKeys:["apiKey"]}],validateCredentials:xIA,normalizeHeaders:mIA})});var weA;var aeA=D(()=>{eA();weA=V({id:"slack",label:"Slack",iconKey:"slack",defaultServerUrl:"https://mcp.slack.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"disabled",oauth:{providerConfigKey:"slack",callbackPathSegment:"slack",authorizationUrl:"https://slack.com/oauth/v2_user/authorize",tokenUrl:"https://slack.com/api/oauth.v2.user.access"},getAvailableScopes:async()=>[{value:"search:read.public"},{value:"search:read.private"},{value:"search:read.mpim"},{value:"search:read.im"},{value:"search:read.files"},{value:"search:read.users"},{value:"canvases:read"},{value:"users:read"},{value:"users:read.email"}],getUrlConfiguration:async()=>null,capabilityOverrides:{defaultUnavailableReason:"write_blocked"},evidenceHints:["Slack app manifests, bot/webhook URLs, SLACK_* environment variables, or slack.com links","Runbooks that route incidents, alerts, or deploy notices through Slack","Code or docs naming Slack channels for operational triage"],helpText:"Browse Slack messages, files, and threads. Coming soon — requires backend OAuth plumbing for user_scope and isn't self-serve connectable yet.",skill:"slack",setupSkill:"slack-setup"})});var reA;var beA=D(()=>{eA();reA=V({id:"stripe",label:"Stripe MCP",iconKey:"stripe",defaultServerUrl:"https://mcp.stripe.com",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"stripe",callbackPathSegment:"stripe",authorizationUrl:"https://access.stripe.com/mcp/oauth2/authorize",tokenUrl:"https://access.stripe.com/mcp/oauth2/token",resourceUrl:"https://mcp.stripe.com",dynamicClientRegistration:{registrationEndpoint:"https://access.stripe.com/mcp/oauth2/register",tokenEndpointAuthMethod:"none"},defaultAccessTokenTtlSeconds:21600},getAvailableScopes:async()=>[{value:"mcp",label:"MCP access",description:"Access the Stripe MCP server tools for the connected account.",required:!0}],scopesUserSelectable:!1,getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Stripe dashboard URLs, `sk_`/`rk_`/`pk_` API keys, or Stripe object IDs (cus_, pi_, ch_)","STRIPE_* environment variables or code that imports the `stripe` SDK","README/runbooks naming Stripe for billing, payments, or subscriptions"],helpText:"Query and manage Stripe payments, customers, and billing."})});var NeA;var ueA=D(()=>{eA();NeA=V({id:"supabase",label:"Supabase",iconKey:"supabase",defaultServerUrl:"https://mcp.supabase.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"supabase",callbackPathSegment:"supabase",authorizationUrl:"https://api.supabase.com/v1/oauth/authorize",tokenUrl:"https://api.supabase.com/v1/oauth/token",dynamicClientRegistration:{registrationEndpoint:"https://api.supabase.com/platform/oauth/apps/register",tokenEndpointAuthMethod:"client_secret_post"}},scopesUserSelectable:!1,getAvailableScopes:async()=>[{value:"analytics:read"},{value:"auth:read"},{value:"auth:write"},{value:"database:read"},{value:"database:write"},{value:"domains:read"},{value:"domains:write"},{value:"edge_functions:read"},{value:"edge_functions:write"},{value:"environment:read"},{value:"environment:write"},{value:"organizations:read"},{value:"projects:read"},{value:"projects:write"},{value:"rest:read"},{value:"rest:write"},{value:"secrets:read"},{value:"secrets:write"},{value:"storage:read"}],getUrlConfiguration:async()=>({docsUrl:"https://supabase.com/docs/guides/getting-started/mcp#step-2-configure-your-ai-tool",instructions:"Choose your project and options in the Supabase configuration panel, then copy the generated Server URL.",defaultServerUrl:"https://mcp.supabase.com/mcp",optional:!0}),capabilityOverrides:{allowWriteTools:!0},evidenceHints:["supabase/ directory, supabase/config.toml, or @supabase packages","SUPABASE_* or NEXT_PUBLIC_SUPABASE_* environment variables","README/docs naming Supabase for Postgres, Auth, Storage, or Edge Functions"],helpText:"Manage Supabase organizations, projects, databases, and run SQL.",skill:"supabase",setupSkill:"supabase-setup"})});var UeA;var FeA=D(()=>{eA();UeA=V({id:"superhuman",label:"Superhuman",iconKey:"superhuman",defaultServerUrl:"https://mcp.mail.superhuman.com/mcp",transport:"streamable-http",authMode:"oauth",availability:"enabled",oauth:{providerConfigKey:"superhuman",callbackPathSegment:"superhuman",authorizationUrl:"https://mcp.auth.mail.superhuman.com/oauth2/authorize",tokenUrl:"https://mcp.auth.mail.superhuman.com/oauth2/token",dynamicClientRegistration:{registrationEndpoint:"https://mcp.auth.mail.superhuman.com/oauth2/register",tokenEndpointAuthMethod:"none"}},scopesUserSelectable:!1,getAvailableScopes:async()=>[{value:"email",required:!0},{value:"offline_access",required:!0},{value:"openid",required:!0},{value:"profile",required:!0}],getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["Superhuman mail links, SUPERHUMAN_* environment variables, or support workflows naming Superhuman","Customer communication runbooks that depend on email search or drafting","Docs naming Superhuman Mail for sales, support, or founder-led customer comms"],helpText:"Search, draft, send, and triage emails in Superhuman Mail."})});var LeA;var SeA=D(()=>{Jt();eA();LeA=V({id:"the-context-company",label:"The Context Company",iconKey:"the-context-company",defaultServerUrl:"https://api.thecontext.company/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{allowWriteTools:!1},evidenceHints:["The Context Company, context company, or context observability references","insight_search, get_agent_runs, or get_agent_sessions tool usage","THE_CONTEXT_COMPANY_API_KEY or api.thecontext.company in MCP configuration"],helpText:"Query agent insights, runs, and sessions through The Context Company's read-only hosted MCP server.",setupGroups:[{id:"api-key",title:"Create a read-only API key",description:"Create the API key The Context Company's hosted MCP server will use.",body:"Generate a read-only API key on The Context Company's [Access Data page](https://www.thecontextcompany.com/prod/mcp-and-api), then paste the raw key below. Sazabi sends it as `Authorization: Bearer <key>` to `https://api.thecontext.company/mcp`.",fieldKeys:["apiKey"]}],validateCredentials:ZIA,normalizeHeaders:vIA,skill:"the-context-company",setupSkill:"the-context-company-setup"})});var leA;var MeA=D(()=>{eA();leA=V({id:"vercel",label:"Vercel",iconKey:"vercel",defaultServerUrl:"https://mcp.vercel.com",transport:"streamable-http",authMode:"oauth",availability:"disabled",oauth:{providerConfigKey:"vercel",callbackPathSegment:"vercel",authorizationUrl:"https://vercel.com/oauth/authorize",tokenUrl:"https://vercel.com/api/login/oauth/token",resourceUrl:"https://mcp.vercel.com",dynamicClientRegistration:{registrationEndpoint:"https://vercel.com/api/login/oauth/register",tokenEndpointAuthMethod:"none"}},scopesUserSelectable:!1,getAvailableScopes:async()=>[{value:"openid",required:!0},{value:"offline_access",required:!0}],getUrlConfiguration:async()=>null,capabilityOverrides:{allowWriteTools:!0},evidenceHints:["vercel.com links, VERCEL_* environment variables, or a vercel.json in the repo","Deploy workflows or runbooks naming Vercel as the frontend/hosting provider","Vercel project/deployment IDs or preview URLs referenced in docs or CI"],helpText:"Manage Vercel projects, deployments, and access Vercel platform documentation. Coming soon — Vercel's hosted MCP only authorizes allowlisted clients and Sazabi is pending approval, so it isn't connectable yet."})});var YeA;var $eA=D(()=>{Jt();eA();YeA=V({id:"x",label:"X",iconKey:"x",defaultServerUrl:"https://api.x.com/mcp",transport:"streamable-http",authMode:"headers",availability:"enabled",capabilityOverrides:{readOnlyToolNames:["search_news","get_news","get_trends_by_woeid","get_posts_by_ids","get_posts_counts_recent","search_posts_all","get_posts_by_id","get_posts_liking_users","get_posts_quoted_posts","get_posts_reposted_by","get_users_by_usernames","get_users_by_username","get_users_me","search_users","get_users_by_id","get_users_bookmarks","get_users_bookmark_folders","get_users_bookmarks_by_folder_id","get_users_mentions","get_users_timeline","get_users_posts"]},evidenceHints:["X (Twitter) API usage, X_BEARER_TOKEN, or TWITTER_* environment variables","twitter-api-v2, tweepy, or other X/Twitter API client packages","README/docs naming the X API, X Developer Platform, or tweet automation"],helpText:"Search X posts and access real-time X data using your app's app-only Bearer Token.",setupGroups:[{id:"developer-app",title:"Open the X Developer Portal",description:"Use an X developer project/app with access to the X API v2.",body:"Go to the [X Developer Portal](https://developer.x.com/en/portal/dashboard), open the project and app you want Sazabi to use, and confirm the app has access to the API tiers you need. The hosted MCP server lives at `https://api.x.com/mcp`."},{id:"bearer-token",title:"Copy the app's Bearer Token",description:"Copy the app-only Bearer Token the hosted MCP server will use.",body:"In your app's **Keys and tokens**, find the app-only **Bearer Token** and copy it (regenerate it if you don't have it saved). This is the app-only token, not a user OAuth 2.0 access token. Paste the raw token into Sazabi — Sazabi adds the `Bearer ` prefix and sends it in the `Authorization` header.",fieldKeys:["accessToken"]}],validateCredentials:WIA,normalizeHeaders:OIA,skill:"x",setupSkill:"x-setup"})});var GeA,mRt;var JeA=D(()=>{UBA();LBA();lBA();YBA();s0();s0();GBA();TBA();PBA();zBA();vBA();WBA();XBA();KBA();_BA();xBA();dBA();sBA();thA();nhA();QhA();IhA();hhA();ChA();EhA();DhA();ahA();bhA();uhA();FhA();ShA();MhA();$hA();GhA();ThA();PhA();zhA();vhA();WhA();XhA();KhA();_hA();xhA();dhA();shA();teA();neA();QeA();IeA();heA();CeA();EeA();DeA();aeA();beA();ueA();FeA();SeA();MeA();$eA();GeA=[NeA,ghA,ihA,uBA,FBA,SBA,MBA,$BA,kBA,JBA,RBA,fBA,OBA,ZBA,HBA,jBA,mBA,qBA,VBA,pBA,AhA,ohA,BhA,ehA,chA,yhA,whA,rhA,NhA,UhA,LhA,lhA,YhA,khA,JhA,RhA,fhA,OhA,ZhA,VhA,HhA,jhA,mhA,qhA,phA,geA,AeA,ieA,oeA,BeA,eeA,ceA,yeA,weA,reA,UeA,LeA,leA,YeA],mRt=new Map(GeA.map((A)=>[A.id,A]))});var TeA=()=>{};var ReA=()=>{};var PeA=()=>{};var feA=()=>{};var zeA=()=>{};var OeA=()=>{};var veA=()=>{};var ZeA=()=>{};var WeA=()=>{};var VeA=()=>{};var XeA=()=>{};var HeA=()=>{};var KeA=()=>{};var jeA=()=>{};var _eA=()=>{};var meA=()=>{};var xeA=()=>{};var qeA=()=>{};var deA=()=>{};var peA=()=>{};var seA=()=>{};var ACA=()=>{};var tCA=()=>{};var gCA=()=>{};var nCA=()=>{};var iCA=()=>{};var QCA=()=>{};var oCA=()=>{};var ICA=()=>{};var BCA=()=>{};var hCA=()=>{};var eCA=()=>{};var CCA=()=>{};var cCA=()=>{};var ECA=()=>{};var yCA=()=>{};var DCA=()=>{};var wCA=()=>{};var aCA=()=>{};var rCA=()=>{};var bCA=()=>{};var NCA=()=>{};var uCA=()=>{};var UCA=()=>{};var FCA=D(()=>{TeA();ReA();PeA();feA();zeA();OeA();veA();ZeA();WeA();VeA();XeA();HeA();KeA();jeA();_eA();meA();xeA();qeA();deA();peA();seA();ACA();tCA();gCA();nCA();iCA();QCA();oCA();ICA();BCA();hCA();eCA();CCA();cCA();ECA();yCA();DCA();wCA();aCA();rCA();bCA();NCA();uCA();UCA()});var LCA=D(()=>{s0()});var SCA=()=>{};var lCA=D(()=>{p_();qa();kIA();Jt();DBA();wBA();JeA();wf();FCA();LCA();SCA()});var MCA,R3A,YCA,P3A,$CA,af,kCA,GCA,ro,JCA,TCA,RCA,Ne,PCA,fCA,ue,zCA,OCA,Ue,vCA,f3A,ZCA,AN,WCA,VCA,XCA,HCA,Fe,KCA,jCA,Le,_CA,mCA,Se,rf,bf,xCA,qCA,le,dCA,pCA,Me,sCA,z3A,Ye,AcA,tcA,$e,gcA,ncA,ke,icA,QcA,Ge,O3A;var Nf=D(()=>{lCA();TA();jA();MCA=["configured","authorizing","connected","error"],R3A=I.enum(MCA),YCA=["preset","custom"],P3A=I.enum(YCA),$CA=["streamable-http","sse"],af=I.enum($CA),kCA=["none","headers","oauth","aws-sigv4"],GCA=I.enum(kCA),ro=I.object({connectionId:I.string().uuid().describe("Connection ID."),connectionKey:I.string().describe("Stable key used to reference this connector in tool calls."),providerId:I.string().describe('Provider identifier, e.g. "linear".'),displayName:I.string().describe("Human-readable connector name."),source:P3A.describe("Whether the connector is a built-in preset or a custom server."),installStatus:R3A.describe("Current connection lifecycle status."),authMode:GCA.describe("Authentication mode."),transport:af.describe("Transport protocol."),serverUrl:I.string().describe("MCP server URL."),readOnly:I.boolean().describe("Whether the connector is restricted to read-only tools."),management:Mk.describe("Lifecycle owner and supported connector mutations."),enabledToolCount:I.number().int().nonnegative().describe("Number of tools enabled and available for this connector."),connectedAt:I.string().datetime().nullable().describe("When the connector last became connected, if ever."),createdAt:I.string().datetime(),updatedAt:I.string().datetime()}),JCA=I.object({name:I.string().describe("Tool name as invoked."),title:I.string().describe("Human-readable tool title."),description:I.string().describe("Tool description."),isReadOnly:I.boolean().describe("Whether the tool is considered read-only."),enabled:I.boolean().describe("Whether the tool is enabled and available given the connector config.")}),TCA=I.object({projectId:I.string().uuid().optional().describe("Project to list connectors for. Auto-filled from SDK context when omitted."),connectedOnly:I.union([I.boolean(),I.stringbool()]).optional().describe("When true, only return connectors that are connected.")}),RCA=I.object({connectors:I.array(ro)}),Ne=L({operationId:"mcpConnectors.list",description:"List configured MCP connectors within one project with provider, status, and enabled-tool count.",backend:"api",route:{method:"GET",path:"/mcp-connectors",tags:["MCP Connectors"]},input:TCA,output:RCA,pagination:"none",async:"sync"}),PCA=I.object({connectionId:I.string().uuid().describe("Connection ID to fetch."),projectId:I.string().uuid().optional().describe("Project the connector belongs to. Auto-filled from SDK context when omitted.")}),fCA=I.object({connector:ro}),ue=L({operationId:"mcpConnectors.get",description:"Get one configured MCP connector by connection ID.",backend:"api",route:{method:"GET",path:"/mcp-connectors/{connectionId}",tags:["MCP Connectors"]},input:PCA,output:fCA,pagination:"none",async:"sync"}),zCA=I.object({connectionId:I.string().uuid().describe("Connection ID to inspect."),projectId:I.string().uuid().optional().describe("Project the connector belongs to. Auto-filled from SDK context when omitted.")}),OCA=I.object({connector:ro,tools:I.array(JCA)}),Ue=L({operationId:"mcpConnectors.details",description:"Inspect one MCP connector's tool surface, including each tool's name, description, and read-only status.",backend:"api",route:{method:"GET",path:"/mcp-connectors/{connectionId}/details",tags:["MCP Connectors"]},input:zCA,output:OCA,pagination:"none",async:"sync"}),vCA=I.object({providerId:I.string().describe('Provider identifier, e.g. "linear".'),label:I.string().describe("Human-readable provider name."),authMode:GCA.describe("Authentication mode."),availability:I.enum(gh).describe("Whether the provider is enabled or coming soon."),setupSkill:I.string().nullable().describe("Markdown setup skill for AI agents. Null when no skill is available.")}),f3A=I.object({}),ZCA=I.object({providers:I.array(vCA)}),AN=L({operationId:"mcpConnectors.listProviders",description:"List all supported MCP connector providers with their auth mode and setup skill.",backend:"api",route:{method:"GET",path:"/mcp-connectors/providers",tags:["MCP Connectors"]},input:f3A,output:ZCA,pagination:"none",async:"sync"}),WCA=I.object({connectionKey:I.string().describe("Stable key used to call this connector."),displayName:I.string().describe("Human-readable connector name."),providerId:I.string().describe('Provider identifier, e.g. "linear".'),toolCount:I.number().int().nonnegative().describe("Number of executable tools on this connector.")}),VCA=I.object({connectionKey:I.string().describe("Connector that exposes this tool."),toolName:I.string().describe("Tool name as invoked."),providerId:I.string().describe('Provider identifier, e.g. "linear".'),displayName:I.string().describe("Human-readable connector name."),isReadOnly:I.boolean().describe("Whether the tool is considered read-only."),description:I.string().describe("Tool description from the stored snapshot."),score:I.number().describe("BM25 rank score. Zero when enumerating a namespace."),inputSchema:I.record(I.string(),I.unknown()).optional().describe("JSON Schema for the tool's arguments, when requested.")}),XCA=I.object({projectId:I.string().uuid().optional().describe("Project to search connectors in. Auto-filled from SDK context when omitted."),query:I.string().optional().describe("Free-text query over tool names, titles, connector keys, and descriptions. Omit or empty to list connectors, or to enumerate one connector when namespace is set."),namespace:I.string().min(1).optional().describe("Restrict results to one connectionKey or providerId."),limit:I.coerce.number().int().min(1).max(100).default(10).describe("Maximum number of connectors or tool hits to return."),offset:I.coerce.number().int().min(0).default(0).describe("Number of connectors or tool hits to skip."),includeInputSchema:I.union([I.boolean(),I.stringbool()]).optional().describe("When true, tool hits include inputSchema so a caller can execute without a describe round-trip.")}),HCA=I.object({kind:I.enum(["connectors","tools"]).describe("connectors when the query is empty and no namespace is set; tools otherwise."),total:I.number().int().nonnegative().describe("Total matches before limit and offset."),connectors:I.array(WCA).describe("Connector index. Empty when kind is tools."),tools:I.array(VCA).describe("Ranked or enumerated tool hits. Empty when kind is connectors.")}),Fe=L({operationId:"mcpConnectors.search",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.",backend:"api",route:{method:"GET",path:"/mcp-connectors/tools/search",tags:["MCP Connectors"]},input:XCA,output:HCA,pagination:"none",async:"sync"}),KCA=I.object({projectId:I.string().uuid().optional().describe("Project the connector belongs to. Auto-filled from SDK context when omitted."),connectionKey:I.string().min(1).describe("Connector key from search or mcpConnectors.list."),toolName:I.string().min(1).describe("Tool name as invoked.")}),jCA=I.object({connectionKey:I.string().describe("Connector that exposes this tool."),toolName:I.string().describe("Tool name as invoked."),providerId:I.string().describe('Provider identifier, e.g. "linear".'),displayName:I.string().describe("Human-readable connector name."),title:I.string().describe("Human-readable tool title."),description:I.string().describe("Tool description from the stored snapshot."),isReadOnly:I.boolean().describe("Whether the tool is considered read-only."),inputSchema:I.record(I.string(),I.unknown()).describe("JSON Schema for the tool's arguments.")}),Le=L({operationId:"mcpConnectors.describe",description:"Load one executable third-party MCP connector tool, including its input schema.",backend:"api",route:{method:"GET",path:"/mcp-connectors/tools/describe",tags:["MCP Connectors"]},input:KCA,output:jCA,pagination:"none",async:"sync"}),_CA=I.object({projectId:I.string().uuid().optional().describe("Project the connector belongs to. Auto-filled from SDK context when omitted."),connectionKey:I.string().min(1).describe("Connector key from search or mcpConnectors.list."),toolName:I.string().min(1).describe("Tool name as invoked."),arguments:I.record(I.string(),I.unknown()).optional().describe("Arguments matching the tool's input schema.")}),mCA=I.discriminatedUnion("ok",[I.object({ok:I.literal(!0),connectionKey:I.string().describe("Connector that ran the tool."),toolName:I.string().describe("Tool name as invoked."),result:I.unknown().describe("Vendor tool result payload."),structuredContent:I.unknown().optional().describe("Structured content from the vendor when present."),content:I.array(I.record(I.string(),I.unknown())).describe("Raw MCP content parts from the vendor."),text:I.string().nullable().describe("Concatenated text content, if any.")}),I.object({ok:I.literal(!1),code:I.enum(["TOOL_NOT_ENABLED","READ_ONLY","MCP_ERROR"]).describe("Why the tool did not run."),message:I.string().describe("Caller-facing error message.")})]),Se=L({operationId:"mcpConnectors.call",description:"Invoke one executable third-party MCP connector tool using that connection's stored credential.",backend:"api",route:{method:"POST",path:"/mcp-connectors/tools/call",tags:["MCP Connectors"]},input:_CA,output:mCA,pagination:"none",async:"sync"}),rf=I.object({id:I.string().min(1).describe("Stable ID for this header (must be unique within the connector)."),name:I.string().trim().min(1).describe("HTTP header name."),value:I.string().min(1).describe("HTTP header value (passed verbatim).")}),bf=I.object({accessKeyId:I.string().trim().min(1).describe("AWS access key ID."),secretAccessKey:I.string().min(1).describe("AWS secret access key."),sessionToken:I.string().min(1).optional().describe("Optional session token for temporary credentials."),region:I.string().trim().min(1).describe("AWS region.")}),xCA=I.object({projectId:I.string().uuid().optional().describe("Project to create the connector in. Auto-filled from SDK context when omitted."),serverUrl:I.string().url().describe("MCP server URL (must be https)."),transport:af.describe("Transport protocol."),headers:I.array(rf).optional().describe("HTTP headers to send with each request."),awsSigV4:bf.optional().describe("AWS SigV4 credentials for AWS MCP servers."),providerId:I.string().min(1).describe("Built-in preset provider ID (for example, linear or datadog)."),readOnly:I.boolean().optional().describe("Restrict the connector to read-only tools. Defaults to false.")}),qCA=I.object({connector:ro}),le=L({operationId:"mcpConnectors.create",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.",backend:"api",route:{method:"POST",path:"/mcp-connectors",tags:["MCP Connectors"],successStatus:201},input:xCA,output:qCA,pagination:"none",async:"sync"}),dCA=I.object({connectionId:I.string().uuid().describe("Connection ID to update."),projectId:I.string().uuid().optional().describe("Project the connector belongs to. Auto-filled from SDK context when omitted."),serverUrl:I.string().url().optional().describe("New MCP server URL."),transport:af.optional().describe("New transport protocol."),headers:I.array(rf).optional().describe("Complete replacement header set. Replaces all existing headers."),awsSigV4:bf.optional().describe("Replacement AWS SigV4 credentials. Mutually exclusive with headers.")}),pCA=I.object({connector:ro}),Me=L({operationId:"mcpConnectors.update",description:"Deprecated. Preset MCP connector updates are no longer supported via the public API; disconnect and reconnect instead.",backend:"api",route:{method:"PATCH",path:"/mcp-connectors/{connectionId}",tags:["MCP Connectors"]},input:dCA,output:pCA,pagination:"none",async:"sync"}),sCA=I.object({connectionId:I.string().uuid().describe("Connection ID to disconnect."),projectId:I.string().uuid().optional().describe("Project the connector belongs to. Auto-filled from SDK context when omitted.")}),z3A=I.void(),Ye=L({operationId:"mcpConnectors.disconnect",description:"Disconnect and permanently remove an MCP connector.",backend:"api",route:{method:"DELETE",path:"/mcp-connectors/{connectionId}",tags:["MCP Connectors"],successStatus:204},input:sCA,output:z3A,pagination:"none",async:"sync"}),AcA=I.object({connectionId:I.string().uuid().describe("Connection ID to update."),projectId:I.string().uuid().optional().describe("Project the connector belongs to. Auto-filled from SDK context when omitted."),readOnly:I.boolean().describe("True to restrict to read-only tools; false to allow all enabled tools.")}),tcA=I.object({connector:ro}),$e=L({operationId:"mcpConnectors.setReadOnly",description:"Toggle the read-only restriction on an MCP connector.",backend:"api",route:{method:"PATCH",path:"/mcp-connectors/{connectionId}/read-only",tags:["MCP Connectors"]},input:AcA,output:tcA,pagination:"none",async:"sync"}),gcA=I.object({projectId:I.string().uuid().optional().describe("Project to install into. Auto-filled from SDK context when omitted."),providerId:I.string().min(1).describe('Provider ID to install, e.g. "linear".'),requestedScopes:I.array(I.string()).optional().describe("Scopes to request. Defaults to the provider's recommended scope set."),serverUrl:I.string().url().optional().describe("Server URL for multi-region providers; defaults to the provider's primary server."),readOnly:I.boolean().optional().describe("Restrict the connector to read-only tools after install. Defaults to false."),returnTo:I.string().optional().describe("Path to redirect the user to after OAuth completes.")}),ncA=I.object({authorizationUrl:I.string().describe("Authorization URL to open in the user's browser."),connectionId:I.string().uuid().describe("Connection ID to poll for completion via getMcpOAuthInstallAttempt."),expiresAt:I.string().datetime().describe("When the OAuth authorization attempt expires.")}),ke=L({operationId:"mcpConnectors.beginOAuthInstall",description:"Begin an OAuth browser flow to install a preset MCP connector. Opens an authorization URL in the user's browser; poll getMcpOAuthInstallAttempt with the returned connectionId to check completion.",backend:"api",route:{method:"POST",path:"/mcp-connectors/oauth/begin",tags:["MCP Connectors"],successStatus:201},input:gcA,output:ncA,pagination:"none",async:"sync"}),icA=I.object({connectionId:I.string().uuid().describe("Connection ID returned by beginMcpOAuthInstall."),projectId:I.string().uuid().optional().describe("Project the connection belongs to. Auto-filled from SDK context when omitted.")}),QcA=I.object({status:I.enum(["authorizing","connected","error"]).describe("Current install status."),connector:ro.optional().describe("Connector details once connected or in error state.")}),Ge=L({operationId:"mcpConnectors.getOAuthInstallAttempt",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.",backend:"api",route:{method:"GET",path:"/mcp-connectors/oauth/attempts/{connectionId}",tags:["MCP Connectors"]},input:icA,output:QcA,pagination:"none",async:"sync"}),O3A={list:Ne.contract,get:ue.contract,details:Ue.contract,listProviders:AN.contract,search:Fe.contract,describe:Le.contract,call:Se.contract,create:le.contract,update:Me.contract,disconnect:Ye.contract,setReadOnly:$e.contract,beginOAuthInstall:ke.contract,getOAuthInstallAttempt:Ge.contract}});var bo,v3A,Z3A,W3A,V3A,X3A,H3A,K3A,uf,f1t;var tN=D(()=>{TA();jA();bo=I.enum(["admin","member"]),v3A=I.object({id:I.string().min(1),name:I.string(),slug:I.string(),logo:I.string().nullable().optional(),role:bo}),Z3A=I.object({id:I.string().min(1),name:I.string().nullable(),email:I.string().email()}),W3A=I.object({credentialType:I.literal("user"),user:Z3A,activeOrganizationId:I.string().min(1).nullable(),authorizedOrganizationId:I.string().min(1).nullable(),authorizedProjectId:I.string().min(1).nullable(),organizations:I.array(v3A).describe("Organizations the user belongs to, including membership role.")}),V3A=I.object({credentialType:I.literal("secret"),organization:I.object({id:I.string().min(1),name:I.string(),slug:I.string(),logo:I.string().nullable().optional()}),keyName:I.string()}),X3A=I.object({credentialType:I.literal("partner"),superorganization:I.object({id:I.string().uuid(),name:I.string()})}),H3A=I.object({}),K3A=I.discriminatedUnion("credentialType",[W3A,V3A,X3A]),uf=L({operationId:"me.get",description:"Return the identity and available context for the current credential.",backend:"api",route:{method:"GET",path:"/me",tags:["Auth"]},input:H3A,output:K3A,pagination:"none",async:"sync"}),f1t=uf.contract});var ocA,IcA,BcA,j3A,_3A,m3A,x3A,q3A,d3A,Uf,Ff,Lf,p3A,s3A,A7A,t7A,g7A,n7A,Sf,lf,Mf,W1t;var hcA=D(()=>{TA();jA();tN();ocA=I.object({membershipId:I.string().min(1).describe("Organization membership record ID."),userId:I.string().min(1).describe("User ID for the organization member."),name:I.string().nullable().describe("Display name for the member, when available."),email:I.string().email().describe("Email address for the member."),imageUrl:I.string().nullable().describe("Profile image URL for the member, when available."),role:bo.describe("Organization role."),createdAt:I.string().datetime().describe("When the membership was created.")}),IcA=I.object({id:I.string().min(1).describe("Invitation ID."),email:I.string().email().describe("Invited email address."),role:bo.describe("Role the invitee will receive when they accept."),status:I.string().min(1).describe('Invitation status (e.g. "pending").'),createdAt:I.string().datetime().describe("When the invitation was created."),expiresAt:I.string().datetime().describe("When the invitation expires.")}),BcA=I.string().min(1).describe("A user ID, or a URL-encoded email address, of the member."),j3A=I.object({organizationId:I.string().min(1).optional().describe("Organization to list members for. Auto-filled from CLI and SDK context when omitted.")}),_3A=I.object({members:I.array(ocA).describe("Members visible within the selected organization.")}),m3A=I.object({organizationId:I.string().min(1).optional().describe("Organization containing the member. Auto-filled from CLI and SDK context when omitted."),member:BcA.describe("User ID, or URL-encoded email address, of the member to update."),role:bo.describe("Role to assign.")}),x3A=I.object({member:ocA.describe("Updated organization member.")}),q3A=I.object({params:I.object({member:BcA.describe("User ID, or URL-encoded email address, of the member to remove.")}),query:I.object({organizationId:I.string().min(1).optional().describe("Organization containing the member. Auto-filled from CLI and SDK context when omitted.")})}).transform(({params:A,query:t})=>({...t,...A})),d3A=I.object({removedUserId:I.string().min(1).describe("User ID removed from the organization.")}),Uf=L({operationId:"members.list",description:"List members in an organization.",backend:"api",route:{method:"GET",path:"/members",tags:["Members"]},input:j3A,output:_3A,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"}]}}]}),Ff=L({operationId:"members.updateRole",description:"Update a member's organization role.",backend:"api",route:{method:"PATCH",path:"/members/{member}/role",tags:["Members"]},input:m3A,output:x3A,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"}}}]}),Lf=L({operationId:"members.remove",description:"Remove a member from an organization.",backend:"api",route:{method:"DELETE",path:"/members/{member}",tags:["Members"],inputStructure:"detailed"},input:q3A,output:d3A,pagination:"none",async:"sync"}),p3A=I.object({organizationId:I.string().min(1).optional().describe("Organization to invite into. Auto-filled from CLI and SDK context when omitted."),email:I.string().email().describe("Email address to invite."),role:bo.optional().default("member").describe('Role to grant on acceptance. Defaults to "member".')}),s3A=I.object({invitation:IcA.describe("The created pending invitation.")}),A7A=I.object({organizationId:I.string().min(1).optional().describe("Organization to list invitations for. Auto-filled from CLI and SDK context when omitted.")}),t7A=I.object({invitations:I.array(IcA).describe("Pending invitations visible within the selected organization.")}),g7A=I.object({params:I.object({invitationId:I.string().min(1).describe("ID of the invitation to revoke.")}),query:I.object({organizationId:I.string().min(1).optional().describe("Organization containing the invitation. Auto-filled from CLI and SDK context when omitted.")})}).transform(({params:A,query:t})=>({...t,...A})),n7A=I.object({revokedInvitationId:I.string().min(1).describe("ID of the revoked invitation.")}),Sf=L({operationId:"members.invite",description:"Invite a person to the organization by email.",backend:"api",route:{method:"POST",path:"/members/invitations",tags:["Members"],successStatus:201},input:p3A,output:s3A,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"}}}]}),lf=L({operationId:"members.listInvitations",description:"List pending invitations for an organization.",backend:"api",route:{method:"GET",path:"/members/invitations",tags:["Members"]},input:A7A,output:t7A,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"}]}}]}),Mf=L({operationId:"members.revokeInvitation",description:"Revoke a pending invitation.",backend:"api",route:{method:"DELETE",path:"/members/invitations/{invitationId}",tags:["Members"],inputStructure:"detailed"},input:g7A,output:n7A,pagination:"none",async:"sync"}),W1t={list:Uf.contract,updateRole:Ff.contract,remove:Lf.contract,invite:Sf.contract,listInvitations:lf.contract,revokeInvitation:Mf.contract}});var CcA,ccA,gN,EcA,nN,ecA=4194304,Yf,$f,i7A=(A)=>{let t=A.split(",").map((i)=>i.trim()).filter(Boolean),g=I.array(gN).safeParse(t);if(!g.success)throw Error("Kind filter must be a comma-separated list of note, runbook, or change.");return g.data},cy,kf,Gf,ycA,DcA,wcA,acA,rcA,bcA,NcA,ucA,UcA,FcA,LcA,ScA,Je,Te,Re,Pe,fe,Q7A;var Jf=D(()=>{TA();jA();CcA=["note","runbook"],ccA=["note","runbook","change"],gN=I.enum(ccA),EcA=I.enum(CcA),nN=I.string().min(1).max(512).refine((A)=>!A.startsWith("/"),{message:"Path must be relative without a leading slash."}).describe("Relative memory path, for example AGENTS.md or notes/architecture.md."),Yf=I.string().min(1).refine((A)=>new TextEncoder().encode(A).length<=ecA,{message:`Memory body must be at most ${ecA} bytes (4 MiB).`}).describe("Document body stored in project memory."),$f=I.string().regex(/^(\d+)(s|m|h|d)$/u,"Duration must use s, m, h, or d units, for example 7d or 30m.").describe("Relative time window, for example 7d or 30m."),cy=I.string().min(1).transform(i7A).describe("Comma-separated kinds, for example note,runbook."),kf=I.object({id:I.string().uuid(),projectId:I.string().uuid(),kind:gN,managed:I.boolean(),path:I.string().nullable(),title:I.string().nullable(),contentHash:I.string(),attrs:I.record(I.string(),I.unknown()),createdAt:I.string().datetime(),updatedAt:I.string().datetime()}),Gf=kf.extend({body:Yf}),ycA=I.object({projectId:I.string().uuid().optional().describe("Project that owns the document. Auto-filled from CLI and SDK context when omitted."),path:nN.describe("Relative path for the curated document."),body:Yf,kind:EcA.default("note").describe("Curated document kind. Only note and runbook may be written through the API."),title:I.string().max(500).optional().describe("Optional display title. Defaults to the path basename.")}),DcA=I.object({document:Gf}),wcA=I.object({projectId:I.string().uuid().optional().describe("Project that owns the document. Auto-filled from CLI and SDK context when omitted."),id:I.string().uuid().optional().describe("Document id."),path:nN.optional().describe("Relative curated path.")}).superRefine((A,t)=>{let g=A.id!==void 0,i=A.path!==void 0;if(g===i)t.addIssue({code:"custom",message:"Provide exactly one of id or path."})}),acA=I.object({document:Gf}),rcA=I.object({projectId:I.string().uuid().optional().describe("Project to list memory for. Auto-filled from CLI and SDK context when omitted."),kind:cy.optional(),since:$f.optional().describe("Only return documents updated within this window, for example 7d."),service:I.string().min(1).optional().describe("Filter to documents whose attrs.services contains this value."),pathPrefix:I.string().min(1).optional().describe("Filter to paths starting with this prefix."),managed:I.coerce.boolean().optional(),cursor:I.string().optional().describe("Cursor from a previous response's nextCursor to fetch the next page."),limit:I.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of documents to return per page.")}),bcA=I.object({documents:I.array(kf),nextCursor:I.string().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),NcA=I.object({documentId:I.string().uuid(),kind:gN,managed:I.boolean(),path:I.string().nullable(),title:I.string().nullable(),snippet:I.string(),score:I.number()}),ucA=I.object({calibrated:I.literal(!0),minScoreThreshold:I.number(),queryTerms:I.array(I.string()),message:I.string()}),UcA=I.object({projectId:I.string().uuid().optional().describe("Project to search memory for. Auto-filled from CLI and SDK context when omitted."),query:I.string().trim().min(1).max(500).describe("Natural-language search query."),kind:cy.optional(),since:$f.optional(),service:I.string().min(1).optional(),pathPrefix:I.string().min(1).optional(),managed:I.coerce.boolean().optional(),limit:I.coerce.number().int().min(1).max(50).default(10).describe("Maximum ranked search hits to return.")}),FcA=I.object({hits:I.array(NcA),emptyVerdict:ucA.nullable()}),LcA=I.object({projectId:I.string().uuid().optional().describe("Project that owns the document. Auto-filled from CLI and SDK context when omitted."),id:I.string().uuid().optional().describe("Document id."),path:nN.optional()}).superRefine((A,t)=>{let g=A.id!==void 0,i=A.path!==void 0;if(g===i)t.addIssue({code:"custom",message:"Provide exactly one of id or path."})}),ScA=I.void(),Je=L({operationId:"memory.put",description:"Create or replace a curated project memory document. Embeds on success.",backend:"api",route:{method:"PUT",path:"/memory",tags:["Memory"]},input:ycA,output:DcA,pagination:"none",async:"sync"}),Te=L({operationId:"memory.get",description:"Get one project memory document by id or path.",backend:"api",route:{method:"GET",path:"/memory/document",tags:["Memory"]},input:wcA,output:acA,pagination:"none",async:"sync"}),Re=L({operationId:"memory.list",description:"List project memory catalog rows without embedding search.",backend:"api",route:{method:"GET",path:"/memory",tags:["Memory"]},input:rcA,output:bcA,pagination:"cursor",async:"sync"}),Pe=L({operationId:"memory.search",description:"Hybrid semantic and keyword search over project memory documents.",backend:"api",route:{method:"POST",path:"/memory/search",tags:["Memory"]},input:UcA,output:FcA,pagination:"none",async:"sync"}),fe=L({operationId:"memory.delete",description:"Soft-delete a curated project memory document by id or path.",backend:"api",route:{method:"DELETE",path:"/memory/document",successStatus:204,tags:["Memory"]},input:LcA,output:ScA,pagination:"none",async:"sync"}),Q7A={put:Je.contract,get:Te.contract,list:Re.contract,search:Pe.contract,delete:fe.contract}});var lcA,McA,o7A,I7A,B7A,h7A,e7A,Ey,C7A,c7A,E7A,Tf,Rf,Pf,ff,m1t;var iN=D(()=>{TA();jA();lcA=I.enum(["processing","completed","aborted","error"]),McA=I.object({id:I.string().uuid(),threadId:I.string().uuid(),userMessageId:I.string().uuid().nullable(),assistantMessageId:I.string().uuid().nullable(),parentRunId:I.string().uuid().nullable(),workflowRunId:I.string().nullable(),status:lcA,source:I.enum(["app","api","mcp","slack","teams","linear","github","agent","cli","web","sdk","bitbucket","system"]),createdAt:I.string().datetime(),updatedAt:I.string().datetime(),completedAt:I.string().datetime().nullable()}),o7A=I.object({projectId:I.string().uuid().optional().describe("Project ID to list runs for. Auto-filled from CLI and SDK context when omitted."),limit:I.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of runs to return per page."),cursor:I.string().datetime().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),I7A=I.object({runs:I.array(McA),nextCursor:I.string().datetime().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),B7A=I.object({threadId:I.string().uuid().describe("Thread ID to list runs for."),limit:I.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of runs to return per page."),cursor:I.string().datetime().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),h7A=I.object({runs:I.array(McA),nextCursor:I.string().datetime().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),e7A=I.object({runId:I.string().uuid().describe("Run ID returned by a deferred operation.")}),Ey=I.object({completed:I.boolean().describe("Whether the run has reached a terminal status."),threadId:I.string().uuid().describe("Thread ID associated with the run."),runId:I.string().uuid().describe("Run ID for subsequent polling."),messageId:I.string().uuid().optional().describe("ID of the user message that triggered this run."),status:lcA.describe("Current run lifecycle status."),response:I.string().nullable().describe("Assistant response text when the run has completed.")}),C7A=Ey.describe("Current run state and, when complete, the assistant response."),c7A=I.object({runId:I.string().uuid().describe("Run ID of the in-flight run to request cancellation for.")}),E7A=I.object({success:I.literal(!0).describe("Always true when the cancellation request was accepted.")}),Tf=L({operationId:"runs.list",description:"List deferred runs within one project.",backend:"api",route:{method:"GET",path:"/runs",tags:["Runs"]},input:o7A,output:I7A,pagination:"cursor",async:"sync"}),Rf=L({operationId:"runs.listForThread",summary:"List Runs for a Thread",description:"List deferred runs for one thread.",backend:"api",route:{method:"GET",path:"/threads/{threadId}/runs",tags:["Runs"]},input:B7A,output:h7A,pagination:"cursor",async:"sync"}),Pf=L({operationId:"runs.get",description:"Get the current result for a deferred run by run ID.",backend:"api",route:{method:"GET",path:"/runs/{runId}",tags:["Runs"]},input:e7A,output:C7A,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}}]}),ff=L({operationId:"runs.cancel",description:"Request cancellation of an in-flight run. Idempotent and best-effort: returns success even when the run has already reached a terminal status.",backend:"api",route:{method:"POST",path:"/runs/{runId}/cancel",tags:["Runs"]},input:c7A,output:E7A,pagination:"none",async:"sync",examples:[{name:"cancel-processing-run",input:{runId:"33333333-3333-4333-8333-333333333333"},output:{success:!0}}]}),m1t={list:Tf.contract,listForThread:Rf.contract,get:Pf.contract,cancel:ff.contract}});var QN=(A,t,g)=>{let i=t?20000:1e4;if(A.length>i)g.addIssue({code:"too_big",maximum:i,type:"string",inclusive:!0,message:`Message cannot exceed ${i} characters`,origin:"string",path:["message"]})},oN=(A,t,g)=>{if(A&&!t)g.addIssue({code:"custom",message:"ambientServiceRun requires an automationId",path:["ambientServiceRun"]})};var YcA,yy,y7A,D7A,w7A,a7A,r7A,b7A,N7A,u7A,U7A,zf,F7A,L7A,S7A,l7A,M7A,Y7A,$7A,k7A,G7A,J7A,T7A,R7A,Of,vf,Zf,Wf,Vf,Xf,$cA,P7A,f7A,z7A,O7A,kcA,v7A,Z7A,W7A,V7A,X7A,H7A,WI="22222222-2222-4222-8222-222222222222",GcA="11111111-1111-4111-8111-111111111111",K7A="44444444-4444-4444-8444-444444444444",JcA="55555555-5555-4555-8555-555555555555",Hf,Kf,jf,_f,mf,tvt;var xf=D(()=>{TA();jA();iN();YcA=I.enum(["slack","teams","linear","github","app","mcp","agent","api","cli","web","sdk","bitbucket","system"]),yy=I.object({id:I.string().uuid(),projectId:I.string().uuid(),title:I.string().nullable(),status:I.enum(["regular","archived"]),source:YcA.nullable(),createdAt:I.string().datetime(),updatedAt:I.string().datetime()}),y7A=I.object({type:I.literal("message"),message:I.string()}),D7A=I.object({type:I.literal("reasoning"),reasoning:I.string(),status:I.enum(["in_progress","complete"]).optional()}),w7A=I.object({type:I.literal("tool_call"),name:I.string(),params:I.any().optional(),result:I.any().optional(),status:I.enum(["in_progress","success","error","unknown"]).optional(),toolCallId:I.string().optional(),durationMs:I.number().nonnegative().optional()}),a7A=I.object({type:I.literal("artifact"),name:I.enum(["timeseries","table","log_detail","integration_required","alert_card","issue_card","mdx"]),data:I.any(),toolCallId:I.string().optional()}),r7A=I.object({type:I.literal("fork"),sourceThreadId:I.string(),sourceMessageId:I.string(),sourceThreadTitle:I.string().nullable()}),b7A=I.object({type:I.literal("summary"),summary:I.string()}),N7A=I.object({type:I.literal("slack_context"),channelId:I.string(),isTruncated:I.boolean().optional(),messages:I.array(I.object({timestamp:I.string(),slackUserId:I.string().optional(),displayName:I.string(),text:I.string(),isBot:I.boolean(),files:I.array(I.object({name:I.string(),mimetype:I.string(),size:I.number().optional(),attachmentId:I.string().uuid().optional(),ingestionStatus:I.enum(["attached","unsupported","oversized","skipped","unavailable"]).optional()})).optional()}))}),u7A=I.object({type:I.literal("teams_context"),conversationId:I.string(),isTruncated:I.boolean().optional(),messages:I.array(I.object({activityId:I.string().optional(),displayName:I.string(),text:I.string(),isBot:I.boolean(),createdDateTime:I.string().optional()}))}),U7A=I.union([y7A,D7A,w7A,a7A,r7A,b7A,N7A,u7A]),zf=I.object({id:I.string().uuid(),role:I.enum(["user","assistant"]),content:I.array(U7A),source:YcA,createdAt:I.string().datetime()}),F7A=I.object({projectId:I.string().uuid().optional().describe("Project to list threads for. Auto-filled from CLI and SDK context when omitted."),limit:I.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of threads to return per page."),cursor:I.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page."),status:I.enum(["regular","archived"]).optional().describe("Filter by thread status. 'regular' returns active threads, 'archived' returns archived threads.")}),L7A=I.object({threads:I.array(yy).describe("The page of threads matching the query."),nextCursor:I.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),S7A=I.object({threadId:I.string().uuid().describe("Thread ID returned by threads.list or threads.create.")}),l7A=I.object({thread:yy.describe("The requested thread."),messages:I.array(zf).describe("Messages currently stored on the thread in chronological order.")}),M7A=I.object({projectId:I.string().uuid().optional().describe("Project to create the thread in. Auto-filled from CLI and SDK context when omitted."),message:I.string().min(1,"Message cannot be empty").describe("Initial user message that starts the thread."),wait:I.boolean().default(!0).describe("Whether the server should wait for the agent run before responding."),timeoutSeconds:I.coerce.number().int().min(1).max(20).default(20).describe("Maximum seconds to wait when wait is true before handing off to polling."),automationId:I.string().uuid().optional().describe("Internal automation context. Set by the Sazabi CLI when an automation script starts an agent run."),ambientServiceRun:I.literal(!0).optional().describe("Internal marker for scheduler-originated ambient service work. Honored only for system secret-key requests with matching automation context.")}).superRefine((A,t)=>{QN(A.message,A.automationId,t),oN(A.ambientServiceRun,A.automationId,t)}),Y7A=Ey.describe("Deferred run result for creating a thread."),$7A=I.object({threadId:I.string().uuid().describe("Thread ID whose current processing status should be returned.")}),k7A=I.object({status:I.enum(["idle","processing"]),lastRunStatus:I.enum(["error"]).nullable()}),G7A=I.object({threadId:I.string().uuid().describe("Thread ID whose active run should be stopped.")}),J7A=I.object({success:I.literal(!0).describe("Always true when the stop request was accepted.")}),T7A=I.object({threadId:I.string().uuid().describe("Thread ID of the thread to update."),status:I.enum(["regular","archived"]).describe("New status for the thread. 'archived' hides the thread from the sidebar.")}),R7A=I.object({thread:yy.describe("The updated thread.")}),Of=L({operationId:"threads.list",description:"List threads in a project, optionally filtered by status.",backend:"api",route:{method:"GET",path:"/threads",tags:["Threads"]},input:F7A,output:L7A,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}}]}),vf=L({operationId:"threads.get",description:"Get a thread and its messages.",backend:"api",route:{method:"GET",path:"/threads/{threadId}",tags:["Threads"]},input:S7A,output:l7A,pagination:"none",async:"sync"}),Zf=L({operationId:"threads.getStatus",description:"Get the current processing status for a thread.",backend:"api",route:{method:"GET",path:"/threads/{threadId}/status",tags:["Threads"]},input:$7A,output:k7A,pagination:"none",async:"sync",examples:[{name:"processing-thread",input:{threadId:"22222222-2222-4222-8222-222222222222"},output:{status:"processing",lastRunStatus:null}}]}),Wf=L({operationId:"threads.stop",description:"Stop a thread's in-flight run. Idempotent and best-effort: returns success even when the thread has no active run.",backend:"api",route:{method:"POST",path:"/threads/{threadId}/stop",tags:["Threads"]},input:G7A,output:J7A,pagination:"none",async:"sync",examples:[{name:"stop-processing-thread",input:{threadId:"22222222-2222-4222-8222-222222222222"},output:{success:!0}}]}),Vf=L({operationId:"threads.create",description:"Create a thread with an initial message and optionally wait for the agent response.",backend:"api",route:{method:"POST",path:"/threads",tags:["Threads"],successStatus:201},input:M7A,output:Y7A,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}}]}),Xf=L({operationId:"threads.update",description:"Update a thread's status.",backend:"api",route:{method:"PATCH",path:"/threads/{threadId}",tags:["Threads"]},input:T7A,output:R7A,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"}}}]}),$cA=I.enum(["private","organization"]),P7A=I.object({threadId:I.string().uuid().describe("Thread ID of the source thread to fork."),messageId:I.string().uuid().describe("Message ID in the source thread to fork from. The new thread copies messages up to and including this message.")}),f7A=I.object({thread:yy.describe("The newly created forked thread.")}),z7A=I.object({threadId:I.string().uuid().describe("Thread ID of the thread to update."),visibility:$cA.describe("New visibility. 'private' restricts the thread to its owner; 'organization' shares it with the organization.")}),O7A=I.object({thread:yy.describe("The updated thread."),visibility:$cA.describe("The thread's resulting visibility.")}),kcA=I.object({shareId:I.string().uuid().describe("Unique identifier for the snapshot."),threadId:I.string().uuid().describe("Thread the snapshot was taken from."),url:I.string().describe("Public read-only URL for the snapshot."),createdAt:I.string().datetime()}),v7A=I.object({threadId:I.string().uuid().describe("Thread ID to create a public read-only snapshot for.")}),Z7A=I.object({share:kcA.describe("The created share link.")}),W7A=I.object({threadId:I.string().uuid().describe("Thread ID the snapshot belongs to."),shareId:I.string().uuid().describe("Snapshot ID to revoke.")}),V7A=I.void(),X7A=I.object({threadId:I.string().uuid().describe("Thread ID to list public snapshots for.")}),H7A=I.object({shares:I.array(kcA).describe("Active share links for the thread.")}),Hf=L({operationId:"threads.fork",description:"Fork a thread from a specific message, creating a new thread that copies messages up to that point.",backend:"api",route:{method:"POST",path:"/threads/{threadId}/fork",tags:["Threads"],successStatus:201},input:P7A,output:f7A,pagination:"none",async:"sync",examples:[{name:"fork-from-message",input:{threadId:WI,messageId:K7A},output:{thread:{id:"66666666-6666-4666-8666-666666666666",projectId:GcA,title:"API returning 500s (fork)",status:"regular",source:"api",createdAt:"2026-01-01T00:20:00.000Z",updatedAt:"2026-01-01T00:20:00.000Z"}}}]}),Kf=L({operationId:"threads.setVisibility",description:"Set a thread's visibility to private or organization.",backend:"api",route:{method:"PATCH",path:"/threads/{threadId}/visibility",tags:["Threads"]},input:z7A,output:O7A,pagination:"none",async:"sync",examples:[{name:"make-private",input:{threadId:WI,visibility:"private"},output:{thread:{id:WI,projectId:GcA,title:"API returning 500s",status:"regular",source:"api",createdAt:"2026-01-01T00:00:00.000Z",updatedAt:"2026-01-01T00:30:00.000Z"},visibility:"private"}}]}),jf=L({operationId:"threads.createShareLink",description:"Create a public read-only share link for a thread's current messages.",backend:"api",route:{method:"POST",path:"/threads/{threadId}/share",tags:["Threads"],successStatus:201},input:v7A,output:Z7A,pagination:"none",async:"sync",examples:[{name:"create-share-link",input:{threadId:WI},output:{share:{shareId:JcA,threadId:WI,url:"https://app.sazabi.com/share/55555555-5555-4555-8555-555555555555",createdAt:"2026-01-01T00:40:00.000Z"}}}]}),_f=L({operationId:"threads.listShareLinks",description:"List active public share links for a thread.",backend:"api",route:{method:"GET",path:"/threads/{threadId}/share",tags:["Threads"]},input:X7A,output:H7A,pagination:"none",async:"sync",examples:[{name:"list-share-links",input:{threadId:WI},output:{shares:[{shareId:JcA,threadId:WI,url:"https://app.sazabi.com/share/55555555-5555-4555-8555-555555555555",createdAt:"2026-01-01T00:40:00.000Z"}]}}]}),mf=L({operationId:"threads.revokeShareLink",description:"Revoke a public share link for a thread.",backend:"api",route:{method:"DELETE",path:"/threads/{threadId}/share/{shareId}",successStatus:204,tags:["Threads"]},input:W7A,output:V7A,pagination:"none",async:"sync"}),tvt={list:Of.contract,get:vf.contract,getStatus:Zf.contract,stop:Wf.contract,create:Vf.contract,update:Xf.contract,fork:Hf.contract,setVisibility:Kf.contract,createShareLink:jf.contract,listShareLinks:_f.contract,revokeShareLink:mf.contract}});var j7A,_7A,m7A,x7A,TcA,RcA;var PcA=D(()=>{TA();jA();iN();xf();j7A=I.object({threadId:I.string().uuid().describe("Thread ID to list messages for."),limit:I.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of messages to return per page."),cursor:I.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page.")}),_7A=I.object({messages:I.array(zf),nextCursor:I.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),m7A=I.object({threadId:I.string().uuid().describe("Thread ID to append the message to."),message:I.string().min(1,"Message cannot be empty").describe("Message body to append to the thread."),wait:I.boolean().default(!0).describe("Whether the server should wait for the appended message run before responding."),timeoutSeconds:I.coerce.number().int().min(1).max(20).default(20).describe("Maximum seconds to wait when wait is true before handing off to polling."),automationId:I.string().uuid().optional().describe("Internal automation context. Set by the Sazabi CLI when an automation script starts an agent run."),ambientServiceRun:I.literal(!0).optional().describe("Internal marker for scheduler-originated ambient service work. Honored only for system secret-key requests with matching automation context.")}).superRefine((A,t)=>{QN(A.message,A.automationId,t),oN(A.ambientServiceRun,A.automationId,t)}),x7A=Ey.describe("Deferred run result for appending a message to an existing thread."),TcA=L({operationId:"messages.list",description:"List messages in a thread with cursor pagination.",backend:"api",route:{method:"GET",path:"/threads/{threadId}/messages",tags:["Messages"]},input:j7A,output:_7A,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}}]}),RcA=L({operationId:"messages.append",description:"Append a user message to an existing thread and trigger a deferred run.",backend:"api",route:{method:"POST",path:"/threads/{threadId}/messages",successStatus:201,tags:["Messages"]},input:m7A,output:x7A,pagination:"none",async:"deferred",examples:[{name:"append-processing",input:{threadId:"22222222-2222-4222-8222-222222222222",message:"Follow up on the intake backlog.",wait:!1,timeoutSeconds:20},output:{completed:!1,threadId:"22222222-2222-4222-8222-222222222222",runId:"33333333-3333-4333-8333-333333333333",status:"processing",response:null}}]})});var En,zcA,qf,ze,df,IN,No,OcA,fcA;var Dy=D(()=>{TA();En={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"},zcA=[En.IN_APP,En.SLACK,En.EMAIL,En.SMS],qf=[En.SLACK_CHANNEL,En.MICROSOFT_TEAMS_CHANNEL,En.INCIDENT_IO,En.PAGERDUTY,En.ROOTLY,En.WEBHOOK],ze=Object.values(En),df=[...ze,"victorops"],IN=I.enum(ze),No=I.enum(qf),OcA=[{channel:"in_app",name:"In-app",description:"Show notifications in your Sazabi notification feed.",scope:"personal",destinationManagement:"none",personalSettingsPath:"/settings/notifications"},{channel:"email",name:"Email",description:"Send notifications to your account email address.",scope:"personal",destinationManagement:"none",personalSettingsPath:"/settings/notifications"},{channel:"sms",name:"SMS",description:"Send notifications to your verified phone number.",scope:"personal",destinationManagement:"none",personalSettingsPath:"/settings/account?phone-number=add"},{channel:"slack",name:"Slack DMs",description:"Send personal notifications by Slack DM.",scope:"personal",destinationManagement:"none",personalSettingsPath:"/settings/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"}],fcA=new Set(OcA.map(({channel:A})=>A));if(fcA.size!==ze.length||ze.some((A)=>!fcA.has(A)))throw Error("Notification channel definitions must represent every channel")});var vcA,q7A=(A,t)=>A.value===t.value&&A.label===t.label&&A.scope===t.scope&&A.role===t.role&&A.defaultOff===t.defaultOff&&(A.defaultOffChannels??[]).join(",")===(t.defaultOffChannels??[]).join(",")&&A.email?.template===t.email?.template&&A.email?.ctaLabel===t.email?.ctaLabel&&(A.deliveryConditions??[]).join(",")===(t.deliveryConditions??[]).join(","),Jg=(A)=>{for(let t of Object.values(A)){let g=vcA.get(t.value);if(g&&!q7A(g,t))throw Error(`Notification type registered twice with conflicting definitions: ${t.value}`);if(t.role!==void 0&&t.scope!=="org")throw Error(`Notification type role restrictions require org scope: ${t.value}`);if(t.label.trim().length===0)throw Error(`Notification type needs a display label: ${t.value}`);if(t.email&&t.email.ctaLabel.trim().length===0)throw Error(`Notification email presentation needs a CTA label: ${t.value}`);if(t.defaultOff&&t.defaultOffChannels)throw Error(`Notification type declares both defaultOff and defaultOffChannels: ${t.value}`);vcA.set(t.value,t)}return A};var eQ=D(()=>{vcA=new Map});var ZcA;var WcA=D(()=>{eQ();ZcA=Jg({AUTOMATION_FINISHED:{value:"automation_finished",label:"Automation completed",scope:"project",defaultOff:!0},AUTOMATION_RUN_FAILED:{value:"automation_run_failed",label:"Automation run failed",scope:"project"}})});var BN;var pf=D(()=>{eQ();BN=Jg({BILLING_PLAN_UPGRADE_APPLIED:{value:"billing_plan_upgrade_applied",label:"Billing upgrade applied",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage billing"}},BILLING_PLAN_DOWNGRADE_SCHEDULED:{value:"billing_plan_downgrade_scheduled",label:"Billing downgrade scheduled",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage billing"}},BILLING_PLAN_DOWNGRADE_APPLIED:{value:"billing_plan_downgrade_applied",label:"Billing downgrade applied",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage billing"}},BILLING_CREDIT_BALANCE_LOW:{value:"billing_credit_balance_low",label:"Billing credits low",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage credits"}},BILLING_CREDIT_BALANCE_DEPLETED:{value:"billing_credit_balance_depleted",label:"Billing credits depleted",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage credits"}},BILLING_AUTO_TOP_UP_SETTINGS_CHANGED:{value:"billing_auto_top_up_settings_changed",label:"Billing auto top-up changed",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage auto top-up"}},BILLING_AUTO_TOP_UP_FAILED:{value:"billing_auto_top_up_failed",label:"Billing auto top-up failed",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage payment method"}},BILLING_INVOICE_PAID:{value:"billing_invoice_paid",label:"Billing invoice paid",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"View invoice"}},BILLING_INVOICE_PAYMENT_FAILED:{value:"billing_invoice_payment_failed",label:"Billing invoice payment failed",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Update payment method"}},BILLING_SUBSCRIPTION_CANCELLATION_SCHEDULED:{value:"billing_subscription_cancellation_scheduled",label:"Billing cancellation scheduled",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage subscription"}},BILLING_SUBSCRIPTION_CANCELED:{value:"billing_subscription_canceled",label:"Billing subscription canceled",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"View billing"}},BILLING_PAYMENT_METHOD_EXPIRING:{value:"billing_payment_method_expiring",label:"Billing payment method expiring",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Update payment method"}},BILLING_PAYMENT_METHOD_CHANGED:{value:"billing_payment_method_changed",label:"Billing payment method changed",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Review payment method"}},BILLING_NEGATIVE_BALANCE_COLLECTED:{value:"billing_negative_balance_collected",label:"Billing outstanding balance charged",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"View billing"}},BILLING_NEGATIVE_BALANCE_COLLECTION_FAILED:{value:"billing_negative_balance_collection_failed",label:"Billing outstanding balance charge failed",scope:"org",role:"admin",email:{template:"billing",ctaLabel:"Manage payment method"}}})});var VcA;var XcA=D(()=>{eQ();VcA=Jg({INTEGRATION_CONNECTED:{value:"integration_connected",label:"Integration connected",scope:"org",defaultOff:!0},INTEGRATION_DISCONNECTED:{value:"integration_disconnected",label:"Integration disconnected",scope:"org"}})});var HcA;var KcA=D(()=>{eQ();HcA=Jg({ISSUE_TRIGGERED:{value:"issue_triggered",label:"Issue triggered",scope:"project",deliveryConditions:["component","severity"]},ISSUE_RESOLVED:{value:"issue_resolved",label:"Issue resolved",scope:"project",defaultOffChannels:["email"],deliveryConditions:["component","severity"]},ISSUE_IGNORED:{value:"issue_ignored",label:"Issue ignored",scope:"project",defaultOffChannels:["email"],deliveryConditions:["component","severity"]}})});var jcA;var _cA=D(()=>{eQ();jcA=Jg({PROJECT_CREATED:{value:"project_created",label:"Project created",scope:"org",defaultOff:!0},PROJECT_DELETED:{value:"project_deleted",label:"Project deleted",scope:"org",defaultOff:!0},MEMBER_INVITED:{value:"member_invited",label:"Member invited",scope:"org",defaultOff:!0},USER_REMOVED:{value:"user_removed",label:"Member removed",scope:"org",defaultOff:!0},MCP_CONNECTOR_ADDED:{value:"mcp_connector_added",label:"MCP connector added",scope:"org",defaultOff:!0},MCP_CONNECTOR_REMOVED:{value:"mcp_connector_removed",label:"MCP connector removed",scope:"org",defaultOff:!0},SECRET_KEY_CREATED:{value:"secret_key_created",label:"Secret key created",scope:"org",defaultOff:!0},SECRET_KEY_DELETED:{value:"secret_key_deleted",label:"Secret key deleted",scope:"org",defaultOff:!0}})});var mcA;var xcA=D(()=>{eQ();mcA=Jg({SANDBOX_CREATED:{value:"sandbox_created",label:"Sandbox connected",scope:"project",defaultOff:!0},SANDBOX_DELETED:{value:"sandbox_deleted",label:"Sandbox disconnected",scope:"project",defaultOff:!0},LOG_SOURCE_CONNECTED:{value:"log_source_connected",label:"Log source connected",scope:"project",defaultOff:!0},LOG_SOURCE_DISCONNECTED:{value:"log_source_disconnected",label:"Log source disconnected",scope:"project"},GITHUB_CONNECTED:{value:"github_connected",label:"GitHub connected",scope:"project",defaultOff:!0},GITHUB_DISCONNECTED:{value:"github_disconnected",label:"GitHub disconnected",scope:"project"},CODE_REPO_CONNECTED:{value:"code_repo_connected",label:"Code repository connected",scope:"project",defaultOff:!0},CODE_REPO_DISCONNECTED:{value:"code_repo_disconnected",label:"Code repository disconnected",scope:"project"},PUBLIC_KEY_DEACTIVATED:{value:"public_key_deactivated",label:"Public key deactivated",scope:"project"}})});var qcA;var dcA=D(()=>{eQ();qcA=Jg({SECURITY_ALERT:{value:"security_alert",label:"Security alert",scope:"org",role:"admin"}})});var sf,Mt,p7A,Az=(A)=>{let t=p7A.get(A)?.label;if(t)return t;let g=A.replace(/_/g," ").trim();return g?g.charAt(0).toUpperCase()+g.slice(1):A};var wy=D(()=>{WcA();pf();pf();XcA();KcA();_cA();xcA();dcA();eQ();sf={...qcA,...jcA,...VcA,...ZcA,...HcA,...mcA,...BN},Mt=Object.fromEntries(Object.entries(sf).map(([A,t])=>[A,t.value])),p7A=new Map(Object.values(sf).map((A)=>[A.value,A]))});var hN,scA,zvt,Pi,Ovt;var VI=D(()=>{wy();Dy();Dy();hN=Object.values(Mt),scA=[Mt.BILLING_PLAN_UPGRADE_APPLIED,Mt.BILLING_PLAN_DOWNGRADE_SCHEDULED,Mt.BILLING_PLAN_DOWNGRADE_APPLIED,Mt.BILLING_CREDIT_BALANCE_LOW,Mt.BILLING_CREDIT_BALANCE_DEPLETED,Mt.BILLING_AUTO_TOP_UP_SETTINGS_CHANGED,Mt.BILLING_AUTO_TOP_UP_FAILED,Mt.BILLING_INVOICE_PAID,Mt.BILLING_NEGATIVE_BALANCE_COLLECTED,Mt.BILLING_NEGATIVE_BALANCE_COLLECTION_FAILED,Mt.BILLING_INVOICE_PAYMENT_FAILED,Mt.BILLING_SUBSCRIPTION_CANCELLATION_SCHEDULED,Mt.BILLING_SUBSCRIPTION_CANCELED,Mt.BILLING_PAYMENT_METHOD_EXPIRING,Mt.BILLING_PAYMENT_METHOD_CHANGED],zvt=new Set(scA),Pi=[Mt.ISSUE_TRIGGERED,Mt.ISSUE_RESOLVED,Mt.ISSUE_IGNORED,Mt.AUTOMATION_RUN_FAILED],Ovt=new Set(Pi)});var ay,AEA,tEA=(A)=>typeof A==="string"&&(A in AEA)?AEA[A]:A,AxA;var gEA=D(()=>{Dy();TA();VI();ay=I.enum(hN),AEA={data_source_connected:"log_source_connected",data_source_disconnected:"log_source_disconnected"},AxA=I.preprocess(tEA,ay)});var txA;var nEA=D(()=>{wy();VI();txA=Pi.map((A)=>({notificationType:A,label:Az(A)}))});var iEA=D(()=>{wy();VI()});var QEA=D(()=>{Dy();wy();VI();gEA();nEA();iEA()});var oEA=()=>{};var IEA=D(()=>{VI()});var BEA=D(()=>{VI()});var tz=D(()=>{oEA();IEA();BEA();QEA()});var QxA,oxA,IxA,BxA,hxA,exA,CxA,gz,A4t;var hEA=D(()=>{tz();TA();jA();QxA=I.enum(["ready","missing","degraded","unavailable"]),oxA=I.object({id:I.string(),label:I.string(),status:I.enum(["active","inactive","degraded"]),statusLabel:I.string()}),IxA=I.object({channel:IN,name:I.string(),description:I.string(),scope:I.enum(["personal","project"]),enabled:I.boolean().nullable(),preferenceId:I.string().nullable(),prerequisite:I.object({status:QxA,statusLabel:I.string(),message:I.string()}),action:I.object({label:I.string(),href:I.string()}).nullable(),destinations:I.array(oxA),destinationManagement:I.enum(["none","slack_channels","teams_channels","integration_connections","webhook_endpoints"]),canCreateDestinations:I.boolean(),supportedNotificationTypes:I.array(ay)}),BxA=I.object({channel:No,enabled:I.boolean(),preferenceId:I.string().nullable()}),hxA=I.object({channel:No,notificationType:ay,enabled:I.boolean(),preferenceId:I.string()}),exA=I.object({projectId:I.string().uuid().optional().describe("Project to inspect. Auto-filled from CLI and SDK context when omitted.")}),CxA=I.object({channelCards:I.array(IxA).length(10),channels:I.array(BxA),notificationTypePreferences:I.array(hxA),issueNotificationMinSeverity:I.enum(["low","medium","high","critical"])}),gz=L({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.",backend:"api",route:{method:"GET",path:"/notification-channels",tags:["Notification channels"]},input:exA,output:CxA,pagination:"none",async:"sync"}),A4t={getProject:gz.contract}});var eEA,iz,CEA,Qz,Q4t,o4t,oz,Iz=(A,t)=>{if((A.componentIds?.length||A.componentId)&&"componentIds"in A.condition&&A.condition.componentIds?.length)t.addIssue({code:"custom",path:["condition","componentIds"],message:"Use componentIds instead of legacy condition.componentIds."});if(A.componentIds?.length&&A.componentId)t.addIssue({code:"custom",path:["componentId"],message:"Use componentIds instead of componentId."})},I4t,cEA,nz,Bz,ry,EEA,cxA,ExA,yxA,DxA,wxA,axA,rxA,bxA,NxA,hz,ez,Cz,cz,Ez,B4t;var yEA=D(()=>{tz();TA();jA();eEA=I.enum(["low","medium","high","critical"]),iz=I.object({severities:I.array(eEA).min(1).optional()}).strict(),CEA=I.object({componentIds:I.array(I.string().uuid()).min(1).optional(),severities:I.array(eEA).min(1).optional()}).strict(),Qz=I.object({channel:No,destinationKey:I.string().min(1)}),Q4t=I.object({destinations:I.array(Qz).min(1),notificationTypes:I.array(I.enum(Pi)).min(1),componentIds:I.array(I.string().uuid()).min(1).optional().describe("Stable component registry IDs matched by this rule."),includeDescendants:I.boolean().default(!1).describe("Whether the rule also matches descendant components."),condition:iz}),o4t=I.object({destinations:I.array(Qz).min(1),notificationTypes:I.array(I.enum(Pi)).min(1),condition:CEA}),oz=I.object({destinations:I.array(Qz).min(1),notificationTypes:I.array(I.enum(Pi)).min(1),componentIds:I.array(I.string().uuid()).min(1).optional().describe("Stable component registry IDs matched by this rule."),componentId:I.string().uuid().optional().describe("Deprecated single-component compatibility input."),includeDescendants:I.boolean().default(!1).describe("Whether the rule also matches descendant components."),condition:I.union([iz,CEA])}),I4t=oz.superRefine(Iz),cEA=I.object({id:I.string(),channel:No,destinationKey:I.string(),displayName:I.string()}),nz=I.object({id:I.string().uuid(),label:I.string(),lifecycle:I.enum(["active","retired","merged"])}),Bz=I.object({id:I.string().uuid(),projectId:I.string().uuid(),notificationTypes:I.array(I.enum(Pi)),destinations:I.array(cEA),condition:iz,component:nz.nullable(),componentId:I.string().uuid().nullable(),includeDescendants:I.boolean(),suspendedAt:I.string().datetime().nullable(),suspensionReason:I.string().nullable(),components:I.array(nz),createdAt:I.string().datetime(),updatedAt:I.string().datetime()}),ry=I.object({projectId:I.string().uuid().optional().describe("Project whose notification delivery rules are being managed.")}),EEA=I.string().uuid().describe("Logical notification delivery rule ID."),cxA=ry,ExA=I.object({rules:I.array(Bz)}),yxA=I.object({destinations:I.array(cEA),notificationTypes:I.array(I.object({notificationType:I.enum(Pi),label:I.string(),conditions:I.array(I.enum(["component","severity"]))})),components:I.array(nz)}),DxA=ry.extend(oz.shape).superRefine(Iz),wxA=Bz,axA=ry.extend({...oz.shape,ruleId:EEA}).superRefine(Iz),rxA=Bz,bxA=ry.extend({ruleId:EEA}),NxA=I.object({removed:I.boolean()}),hz=L({operationId:"notificationDeliveryRules.list",description:"List the positive delivery rules for a project.",backend:"api",route:{method:"GET",path:"/notification-delivery-rules",tags:["Notification delivery rules"]},input:cxA,output:ExA,pagination:"none",async:"sync"}),ez=L({operationId:"notificationDeliveryRules.options",description:"List available destinations, events, and conditions for project delivery rules.",backend:"api",route:{method:"GET",path:"/notification-delivery-rules/options",tags:["Notification delivery rules"]},input:ry,output:yxA,pagination:"none",async:"sync"}),Cz=L({operationId:"notificationDeliveryRules.create",description:"Create a positive project notification delivery rule.",backend:"api",route:{method:"POST",path:"/notification-delivery-rules",tags:["Notification delivery rules"]},input:DxA,output:wxA,pagination:"none",async:"sync"}),cz=L({operationId:"notificationDeliveryRules.update",description:"Replace a positive delivery rule atomically.",backend:"api",route:{method:"PUT",path:"/notification-delivery-rules/{ruleId}",tags:["Notification delivery rules"]},input:axA,output:rxA,pagination:"none",async:"sync"}),Ez=L({operationId:"notificationDeliveryRules.delete",description:"Delete a positive delivery rule without deleting its reusable destinations.",backend:"api",route:{method:"DELETE",path:"/notification-delivery-rules/{ruleId}",tags:["Notification delivery rules"]},input:bxA,output:NxA,pagination:"none",async:"sync"}),B4t={list:hz.contract,options:ez.contract,create:Cz.contract,update:cz.contract,delete:Ez.contract}});var yz,uxA,UxA,FxA,LxA,SxA,lxA,Dz,MxA,YxA,wz,$xA,kxA,az,GxA,JxA,rz,TxA,RxA,bz,c4t;var DEA=D(()=>{TA();jA();yz=I.enum(["verify-email","accept-invite","create-organization","billing","configure-project","connect-github-account","install-github-app","configure-code-search","install-slack-app","configure-slack-notifications","trigger-issue","confirm-issue","finish"]),uxA=I.enum(["needs-onboarding","blocked","ready"]),UxA=I.enum(["incomplete","complete","skipped"]),FxA=I.object({invitationId:I.string(),organizationId:I.string(),organizationName:I.string(),organizationSlug:I.string(),organizationImageUrl:I.string().nullable(),inviterName:I.string().nullable()}),LxA=I.object({gate:uxA,canonicalStep:yz.nullable(),organizationId:I.string().nullable(),projectId:I.string().nullable(),completionByStep:I.record(yz,UxA),githubSkipped:I.boolean(),githubAppSkipped:I.boolean(),slackSkipped:I.boolean(),sampleIssueId:I.string().nullable(),actorRole:I.enum(["admin","member"]).nullable(),requiredStep:I.union([yz,I.literal("select-organization")]).nullable(),isCompleted:I.boolean(),onboardingRecommendationsThreadId:I.string().nullable(),hasOrganizations:I.boolean(),hasPaidBillingSubscription:I.boolean(),billingStepEnabled:I.boolean(),pendingInvitations:I.array(FxA)}),SxA=I.object({projectId:I.string().uuid().optional().describe("Project whose onboarding state to bind (sample-issue attempt and project-scoped facts). Auto-filled from CLI and SDK context when omitted.")}),lxA=I.object({onboarding:LxA}),Dz=L({operationId:"onboarding.getState",description:"Read onboarding progress for the authenticated user.",backend:"api",route:{method:"GET",path:"/onboarding/state",tags:["Onboarding"]},input:SxA,output:lxA,pagination:"none",async:"sync"}),MxA=I.object({integration:I.enum(["github","slack"]).describe("Integration onboarding step to skip."),projectId:I.string().uuid().optional().describe("Project used to resolve the organization whose onboarding state is written. Without it, the credential's active organization is used — which for CLI user tokens is the server session's organization, not the CLI's selected one.")}),YxA=I.object({skipped:I.literal(!0)}),wz=L({operationId:"onboarding.skipIntegration",description:"Skip a GitHub or Slack integration step during onboarding.",backend:"api",route:{method:"POST",path:"/onboarding/skip-integration",tags:["Onboarding"]},input:MxA,output:YxA,pagination:"none",async:"sync"}),$xA=I.object({projectId:I.string().uuid().optional().describe("Project used to resolve the organization whose onboarding state is written. Without it, the credential's active organization is used — which for CLI user tokens is the server session's organization, not the CLI's selected one.")}),kxA=I.object({skipped:I.literal(!0)}),az=L({operationId:"onboarding.skipGithubAppInstallation",summary:"Skip GitHub App Installation",description:"Skip GitHub App installation during onboarding.",backend:"api",route:{method:"POST",path:"/onboarding/skip-github-app",tags:["Onboarding"]},input:$xA,output:kxA,pagination:"none",async:"sync"}),GxA=I.object({projectId:I.string().uuid().optional().describe("Project used to resolve the organization whose onboarding state is written. Without it, the credential's active organization is used — which for CLI user tokens is the server session's organization, not the CLI's selected one.")}),JxA=I.object({skipped:I.literal(!0)}),rz=L({operationId:"onboarding.skipSampleIssue",summary:"Skip Test Issue",description:"Skip the optional test issue during onboarding.",backend:"api",route:{method:"POST",path:"/onboarding/skip-sample-issue",tags:["Onboarding"]},input:GxA,output:JxA,pagination:"none",async:"sync"}),TxA=I.object({projectId:I.string().uuid().describe("Project that completed onboarding.")}),RxA=I.object({completed:I.boolean()}),bz=L({operationId:"onboarding.finish",description:"Mark onboarding complete when all prerequisites are satisfied.",backend:"api",route:{method:"POST",path:"/onboarding/finish",tags:["Onboarding"]},input:TxA,output:RxA,pagination:"none",async:"sync"}),c4t={getState:Dz.contract,skipIntegration:wz.contract,skipGithubAppInstallation:az.contract,skipSampleIssue:rz.contract,finish:bz.contract}});var eN,PxA,fxA,zxA,OxA,vxA,ZxA,WxA,VxA,XxA,HxA,Nz,uz,Uz,Fz,a4t;var wEA=D(()=>{TA();jA();tN();eN=I.object({id:I.string().min(1),name:I.string(),slug:I.string(),logo:I.string().nullable().optional()}),PxA=eN.extend({role:bo.optional()}),fxA=I.object({}),zxA=I.object({organizations:I.array(PxA).describe("Organizations available to the current credential.")}),OxA=I.object({organizationId:I.string().min(1).describe("Organization ID to fetch.")}),vxA=I.object({organization:eN}),ZxA=I.object({organizationId:I.string().min(1).describe("Organization ID to update. SDK and CLI callers can auto-fill this before dispatch."),name:I.string().trim().min(1).max(100).describe("New organization name.")}),WxA=I.object({organization:eN.describe("Updated organization.")}),VxA=I.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(/^[\p{L}\p{N} _-]+$/u,"Name can only contain letters, numbers, spaces, hyphens, and underscores"),XxA=I.object({name:VxA.describe("Organization display name.")}),HxA=I.object({organization:eN}),Nz=L({operationId:"organizations.create",description:"Create an organization for the authenticated user.",backend:"api",route:{method:"POST",path:"/organizations",tags:["Organizations"],successStatus:201},input:XxA,output:HxA,pagination:"none",async:"sync"}),uz=L({operationId:"organizations.list",description:"List organizations available to the current credential.",backend:"api",route:{method:"GET",path:"/organizations",tags:["Organizations"]},input:fxA,output:zxA,pagination:"none",async:"sync"}),Uz=L({operationId:"organizations.get",description:"Get one organization by ID.",backend:"api",route:{method:"GET",path:"/organizations/{organizationId}",tags:["Organizations"]},input:OxA,output:vxA,pagination:"none",async:"sync"}),Fz=L({operationId:"organizations.update",description:"Update one organization.",backend:"api",route:{method:"PATCH",path:"/organizations/{organizationId}",tags:["Organizations"]},input:ZxA,output:WxA,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}}}]}),a4t={list:uz.contract,get:Uz.contract,create:Nz.contract,update:Fz.contract}});var Oe,by,aEA,rEA,bEA,NEA,uEA,UEA,FEA,CN,cN,EN,LEA,SEA,yN,lEA,MEA,DN,KxA;var Lz=D(()=>{TA();jA();Oe=I.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"]),by=I.object({id:I.string().uuid(),organizationId:I.string().min(1),name:I.string(),region:Oe}),aEA=I.object({organizationId:I.string().min(1).optional().describe("Organization to list projects for. Auto-filled from CLI and SDK context when omitted.")}),rEA=I.object({projects:I.array(by).describe("Projects visible within the selected organization.")}),bEA=I.object({projectId:I.string().uuid().describe("Project ID to fetch.")}),NEA=I.string().trim().min(1,"Name is required").max(100,"Name must be 100 characters or less").regex(/^[\p{L}\p{N} _-]+$/u,"Name can only contain letters, numbers, spaces, hyphens, and underscores"),uEA=I.object({organizationId:I.string().min(1).optional().describe("Organization to create the project under. Auto-filled from CLI and SDK context when omitted."),name:NEA.describe("Project name."),region:Oe.optional().default("us-west-2").describe("AWS region where the new project should be created.")}),UEA=I.object({project:by}),FEA=I.object({project:by}),CN=L({operationId:"projects.list",description:"List projects in an organization.",backend:"api",route:{method:"GET",path:"/projects",tags:["Projects"]},input:aEA,output:rEA,pagination:"none",async:"sync"}),cN=L({operationId:"projects.get",description:"Get one project by ID.",backend:"api",route:{method:"GET",path:"/projects/{projectId}",tags:["Projects"]},input:bEA,output:FEA,pagination:"none",async:"sync"}),EN=L({operationId:"projects.create",description:"Create one project in an organization.",backend:"api",route:{method:"POST",path:"/projects",successStatus:201,tags:["Projects"]},input:uEA,output:UEA,pagination:"none",async:"sync"}),LEA=I.object({projectId:I.string().uuid().describe("Project ID to update."),name:NEA.optional().describe("New project name.")}),SEA=I.object({project:by}),yN=L({operationId:"projects.update",description:"Update (rename) one project by ID. User credentials require the `settings:write` organization permission (admin or owner role).",backend:"api",route:{method:"PATCH",path:"/projects/{projectId}",tags:["Projects"]},input:LEA,output:SEA,pagination:"none",async:"sync"}),lEA=I.object({projectId:I.string().uuid().describe("Project ID to delete.")}),MEA=I.void(),DN=L({operationId:"projects.delete",description:"Delete one project by ID. User credentials require the `settings:write` organization permission (admin or owner role).",backend:"api",route:{method:"DELETE",path:"/projects/{projectId}",successStatus:204,tags:["Projects"]},input:lEA,output:MEA,pagination:"none",async:"sync"}),KxA={list:CN.contract,get:cN.contract,create:EN.contract,update:yN.contract,delete:DN.contract}});var YEA,jxA,_xA,mxA,xxA,qxA,Sz,L4t;var $EA=D(()=>{TA();jA();YEA=I.enum(["open","merged","closed"]),jxA=I.enum(["review_required","approved","changes_requested"]),_xA=I.enum(["passing","failing","pending"]),mxA=I.object({id:I.string().uuid(),projectId:I.string().uuid(),repositoryFullName:I.string(),pullRequestId:I.string().describe("Provider-native pull request identifier (GitHub PR number or Bitbucket PR id), serialized as a string."),githubPullRequestId:I.number().int().describe("Deprecated: use pullRequestId. Numeric form of the provider-native pull request identifier; kept for backward compatibility."),title:I.string().nullable(),url:I.string().nullable(),status:YEA.nullable(),reviewState:jxA.nullable(),checksState:_xA.nullable(),requestedByUserId:I.string().nullable(),authorLogin:I.string().nullable().describe("Forge login that authored the pull request (often the Sazabi app identity)."),githubAuthorLogin:I.string().nullable().describe("Deprecated: use authorLogin. Kept for backward compatibility."),threadId:I.string().uuid().nullable(),runId:I.string().uuid().nullable(),createdAt:I.string().datetime(),mergedAt:I.string().datetime().nullable(),closedAt:I.string().datetime().nullable()}),xxA=I.object({projectId:I.string().uuid().optional().describe("Project to list pull requests for. Auto-filled from CLI and SDK context when omitted."),limit:I.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of pull requests to return per page."),cursor:I.string().uuid().optional().describe("Cursor from a previous response's nextCursor to fetch the next page."),status:YEA.optional().describe("Filter by pull request status (open, merged, or closed)."),repositoryFullName:I.string().trim().optional().describe("Filter by repository full name, for example owner/repo. Case-insensitive."),requestedByUserId:I.string().trim().optional().describe("Filter by the Sazabi user who requested the pull request. Pass 'me' to filter to the authenticated user.")}),qxA=I.object({pullRequests:I.array(mxA),nextCursor:I.string().uuid().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),Sz=L({operationId:"pullRequests.list",description:"List pull requests that Sazabi opened, optionally filtered by status, repository, and requesting user.",backend:"api",route:{method:"GET",path:"/pull-requests",tags:["Pull Requests"]},input:xxA,output:qxA,pagination:"cursor",async:"sync"}),L4t={list:Sz.contract}});var kEA,GEA,JEA,TEA,REA,Ny;var lz=D(()=>{TA();jA();kEA=I.enum(["log_source","mcp_connector","sandbox_cli","integration"]),GEA=I.enum(["connected","recommended"]),JEA=I.object({kind:kEA.describe("What the recommendation targets: a log source, MCP connector, sandbox CLI, or integration."),targetId:I.string().describe("Exact catalog id for the kind (log source type, MCP provider id, sandbox CLI preset type, or integration provider id)."),status:GEA.describe("Resolved live against current connections: connected (already set up) or recommended (suggested, not yet connected)."),roiScore:I.number().int().min(0).max(100).describe("Intrinsic ROI score, 0–100 — a normalized blend of how valuable, how easy to connect, and how proven the item is. A pure function of the item; computed live on read, never stored."),priority:I.number().int().min(1).describe("1-based rank within this list, sorted by roiScore (best first). Items are already returned in priority order; the field lets consumers recover the rank without trusting array position.")}),TEA=I.object({projectId:I.string().uuid().optional().describe("Project to list recommendations for. Auto-filled from CLI and SDK context when omitted.")}),REA=I.object({recommendations:I.array(JEA).describe("The project's configuration recommendations, deduped by (kind, targetId), with status resolved live and each item's ROI score. Returned in priority order (highest roiScore first).")}),Ny=L({operationId:"recommendations.list",description:"List a project's configuration recommendations (data sources, MCP connectors, sandbox CLIs, and integrations) with each item's live connection status.",backend:"api",route:{method:"GET",path:"/recommendations",tags:["Recommendations"]},input:TEA,output:REA,pagination:"none",async:"sync"})});var PEA,Mz,fEA,zEA,OEA,vEA,ZEA,WEA,uy,Uy,Fy;var Yz=D(()=>{TA();jA();PEA=I.enum(["github","bitbucket"]),Mz=I.object({id:I.string().uuid().describe("Repository row id — stable across access sources; use it as the path id for repos.remove."),accessSourceId:I.string().uuid().describe("Access source granting this view of the repository (GitHub App installation, personal connection, or integration). Pass to repos.add to link the repository through this source."),provider:PEA.describe("Forge hosting the repository."),owner:I.string().describe("Repository owner (user or organization)."),name:I.string().describe("Repository name without the owner."),fullName:I.string().describe("Full name in owner/name form."),defaultBranch:I.string().nullable().describe("Default branch, when the forge reports one."),isPrivate:I.boolean().describe("Whether the repository is private."),linked:I.boolean().describe("Whether the repository is already linked to the project.")}),fEA=I.object({projectId:I.string().uuid().optional().describe("Project to list repositories for. Auto-filled from CLI and SDK context when omitted.")}),zEA=I.object({repos:I.array(Mz).describe("Every repository available to the project's organization (from GitHub App installations, the caller's personal forge connections, and integrations), with `linked` marking the ones already linked to the project.")}),OEA=I.object({projectId:I.string().uuid().optional().describe("Project to link the repositories to. Auto-filled from CLI and SDK context when omitted."),accessSourceIds:I.array(I.string().uuid()).min(1).describe("Access source ids (from repos.list) to link. Select only one access source per repository.")}),vEA=I.object({repos:I.array(Mz).describe("The now-linked repositories.")}),ZEA=I.object({id:I.string().uuid().describe("Repository row id (from repos.list) to unlink."),projectId:I.string().uuid().optional().describe("Project to unlink the repository from. Auto-filled from CLI and SDK context when omitted.")}),WEA=I.void(),uy=L({operationId:"repos.list",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.",backend:"api",route:{method:"GET",path:"/repos",tags:["Repos"]},input:fEA,output:zEA,pagination:"none",async:"sync"}),Uy=L({operationId:"repos.add",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.",backend:"api",route:{method:"POST",path:"/repos",tags:["Repos"]},input:OEA,output:vEA,pagination:"none",async:"sync"}),Fy=L({operationId:"repos.remove",description:"Unlink a repository from a project by repository row id.",backend:"api",route:{method:"DELETE",path:"/repos/{id}",successStatus:204,tags:["Repos"]},input:ZEA,output:WEA,pagination:"none",async:"sync"})});var VEA,dxA,XEA,wN,HEA,KEA,jEA,_EA,ve,$z,mEA,xEA,Ze,qEA,dEA,We,pEA,sEA,Ve,pxA;var kz=D(()=>{TA();jA();VEA=I.object({type:I.string().describe("Preset type identifier."),label:I.string().describe("Human-readable display name."),executableNames:I.array(I.string()).describe("CLI binary names installed by this preset."),envVarKeys:I.array(I.string()).describe("Environment variables required for authentication."),setupSkill:I.string().nullable().describe("Markdown setup skill for AI agents. Null when no skill is available.")}),dxA=I.object({}),XEA=I.object({types:I.array(VEA)}),wN=L({operationId:"sandboxPresets.listTypes",description:"List all supported sandbox CLI types with their environment variable requirements and setup skills.",backend:"api",route:{method:"GET",path:"/sandbox-presets/types",tags:["Sandbox Presets"]},input:dxA,output:XEA,pagination:"none",async:"sync"}),HEA=I.enum(["github_app","bitbucket_integration","personal_access_token","stored_credentials"]),KEA=I.object({presetType:I.string().describe("Preset type identifier."),credentialSource:HEA.describe("Authoritative credential source for the preset."),isSystemManaged:I.boolean().describe("Whether the connection follows an integration lifecycle."),fallbackConfigured:I.boolean().describe("Whether user-provided fallback credentials are stored for this preset."),envVarKeys:I.array(I.string()).describe("Stored environment variable names. Secret values are omitted.")}),jEA=I.object({projectId:I.string().uuid().optional().describe("Project to inspect. Required for organization-scoped keys; auto-filled from a project-scoped key when omitted.")}),_EA=I.object({connections:I.array(KEA)}),ve=L({operationId:"sandboxPresets.listConnections",description:"List a project's stored and integration-backed sandbox CLI connections without returning secret values.",backend:"api",route:{method:"GET",path:"/sandbox-presets/connections",tags:["Sandbox Presets"]},input:jEA,output:_EA,pagination:"none",async:"sync"}),$z=I.object({key:I.string().min(1).max(256).regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"Environment variable keys must match /^[A-Za-z_][A-Za-z0-9_]*$/.").describe("Environment variable name (e.g. KUBECONFIG_CONTENTS)."),value:I.string().max(10240).describe("Secret value. Encrypted at rest; never returned by any API response.")}),mEA=I.object({projectId:I.string().uuid().optional().describe("Project to configure. Required for organization-scoped keys; auto-filled from a project-scoped key when omitted."),presetType:I.string().min(1).describe("Preset type identifier (e.g. kubectl, aws, github)."),environmentVariables:I.array($z).max(100).describe("Full set of env vars for this preset. Replaces any previously stored values for the preset.")}),xEA=I.object({projectId:I.string().uuid().describe("Project the preset was written to."),presetType:I.string().describe("Preset type that was upserted."),envVarKeys:I.array(I.string()).describe("Env var key names now stored for this preset. Values are never returned.")}),Ze=L({operationId:"sandboxPresets.upsertPreset",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.",backend:"api",route:{method:"POST",path:"/sandbox-presets/config",successStatus:200,tags:["Sandbox Presets"]},input:mEA,output:xEA,pagination:"none",async:"sync"}),qEA=I.object({projectId:I.string().uuid().optional().describe("Project to update. Required for organization-scoped keys; auto-filled from a project-scoped key when omitted."),presetType:I.string().min(1).describe("Preset type identifier.")}),dEA=I.object({projectId:I.string().uuid().describe("Project the CLI connection belonged to."),presetType:I.string().describe("Preset type that was disconnected."),deleted:I.boolean().describe("Whether a stored CLI connection was deleted.")}),We=L({operationId:"sandboxPresets.deletePreset",summary:"Disconnect CLI",description:"Delete a project's stored CLI connection. Integration-managed access remains available until its owning integration is disconnected.",backend:"api",route:{method:"DELETE",path:"/sandbox-presets/config/{presetType}",tags:["Sandbox Presets"]},input:qEA,output:dEA,pagination:"none",async:"sync"}),pEA=I.object({projectId:I.string().uuid().optional().describe("Project to test from. Required for organization-scoped keys; auto-filled from a project-scoped key when omitted."),presetType:I.string().min(1).describe("Preset type identifier."),environmentVariables:I.array($z).max(100).describe("Unsaved credentials to validate in a readonly sandbox.")}),sEA=I.object({status:I.enum(["success","failed"]),message:I.string().nullable(),stdout:I.string().describe("Truncated command output with submitted credentials redacted."),stderr:I.string().describe("Truncated command errors with submitted credentials redacted.")}),Ve=L({operationId:"sandboxPresets.testPreset",summary:"Test CLI connection",description:"Validate unsaved CLI credentials in a read-only ephemeral sandbox without persisting them.",backend:"api",route:{method:"POST",path:"/sandbox-presets/test",tags:["Sandbox Presets"]},input:pEA,output:sEA,pagination:"none",async:"sync"}),pxA={deletePreset:We.contract,listConnections:ve.contract,listTypes:wN.contract,testPreset:Ve.contract,upsertPreset:Ze.contract}});var aN,AyA=1048576,Gz,tyA,Jz,sxA,AqA,tqA,gqA,nqA,iqA,QqA,oqA,IqA,BqA,Tz,Rz,Pz,fz,zz,z4t;var gyA=D(()=>{TA();jA();aN=I.string().min(1).max(64).regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/,"Name must start with a letter or digit and contain only letters, digits, underscores, and hyphens (max 64 characters).").describe("Script name. Must be unique within the project among non-deleted scripts."),Gz=I.string().min(1).refine((A)=>new TextEncoder().encode(A).length<=AyA,{message:`Script content must be at most ${AyA} bytes (1 MiB).`}).describe("Bash script body materialized as /home/sazabi/scripts/<name>.sh in the sandbox."),tyA=I.object({id:I.string().uuid(),projectId:I.string().uuid(),name:I.string(),description:I.string().nullable(),contentHash:I.string().describe("sha256 hex digest of the script content."),createdAt:I.string().datetime(),updatedAt:I.string().datetime()}),Jz=tyA.extend({content:Gz}),sxA=I.object({projectId:I.string().uuid().optional().describe("Project to list scripts for. Auto-filled from CLI and SDK context when omitted."),search:I.string().optional().describe("Case-insensitive partial match on script name."),cursor:I.string().optional().describe("Cursor from a previous response's nextCursor to fetch the next page."),limit:I.coerce.number().int().min(1).max(100).default(50).describe("Maximum number of scripts to return per page.")}),AqA=I.object({scripts:I.array(tyA),nextCursor:I.string().nullable().describe("Pass as 'cursor' to fetch the next page. Null when there are no more results.")}),tqA=I.object({name:aN.describe("Script name to fetch."),projectId:I.string().uuid().optional().describe("Project that owns the script. Auto-filled from CLI and SDK context when omitted.")}),gqA=I.object({script:Jz}),nqA=I.object({projectId:I.string().uuid().optional().describe("Project that owns the script. Auto-filled from CLI and SDK context when omitted."),name:aN.describe("Script name. Must be unique within the project among non-deleted scripts."),content:Gz,description:I.string().max(500).nullable().optional().describe("Optional human-readable description.")}),iqA=I.object({script:Jz}),QqA=I.object({name:aN.describe("Script to update."),projectId:I.string().uuid().optional().describe("Project that owns the script. Auto-filled from CLI and SDK context when omitted."),content:Gz.optional().describe("New script body. Omit to leave content unchanged."),description:I.string().max(500).nullable().optional().describe("New description, or null to clear it. Omit to leave unchanged.")}),oqA=I.object({script:Jz}),IqA=I.object({name:aN.describe("Script to delete."),projectId:I.string().uuid().optional().describe("Project that owns the script. Auto-filled from CLI and SDK context when omitted.")}),BqA=I.void(),Tz=L({operationId:"scripts.list",description:"List durable bash scripts stored for a project.",backend:"api",route:{method:"GET",path:"/scripts",tags:["Scripts"]},input:sxA,output:AqA,pagination:"cursor",async:"sync"}),Rz=L({operationId:"scripts.get",description:"Get a single project script by name, including its body.",backend:"api",route:{method:"GET",path:"/scripts/{name}",tags:["Scripts"]},input:tqA,output:gqA,pagination:"none",async:"sync"}),Pz=L({operationId:"scripts.create",description:"Create a durable bash script for a project.",backend:"api",route:{method:"POST",path:"/scripts",successStatus:201,tags:["Scripts"]},input:nqA,output:iqA,pagination:"none",async:"sync"}),fz=L({operationId:"scripts.update",description:"Update a project script's body and/or description.",backend:"api",route:{method:"PATCH",path:"/scripts/{name}",tags:["Scripts"]},input:QqA,output:oqA,pagination:"none",async:"sync"}),zz=L({operationId:"scripts.delete",description:"Soft-delete a project script by name.",backend:"api",route:{method:"DELETE",path:"/scripts/{name}",successStatus:204,tags:["Scripts"]},input:IqA,output:BqA,pagination:"none",async:"sync"}),z4t={list:Tz.contract,get:Rz.contract,create:Pz.contract,update:fz.contract,delete:zz.contract}});var Oz,nyA,iyA,QyA,oyA,Xe,He,hqA;var vz=D(()=>{TA();jA();Oz=I.object({projectId:I.string().uuid().optional().describe("Project to search within. Auto-filled from CLI and SDK context when omitted."),query:I.string().trim().min(1,"Query must be at least 1 character").max(500,"Query must be at most 500 characters"),limit:I.coerce.number().min(1).max(100).default(20).describe("Maximum number of search results to return."),page:I.coerce.number().min(1).default(1).describe("One-based page number.")}),nyA=Oz.extend({status:I.enum(["regular","archived"]).optional().describe("Optional thread status filter.")}),iyA=Oz.extend({threadId:I.string().uuid().optional().describe("Optional thread restriction for message search."),role:I.enum(["user","assistant"]).optional().describe("Optional message role filter.")}),QyA=I.object({threads:I.array(I.object({id:I.string().uuid(),projectId:I.string().uuid().optional(),title:I.string(),status:I.enum(["regular","archived"]),labels:I.array(I.string()),createdAt:I.string().datetime(),updatedAt:I.string().datetime(),highlights:I.array(I.string()),score:I.number().optional()})),pagination:I.object({page:I.number(),limit:I.number(),totalResults:I.number(),totalPages:I.number()}).describe("Page-based pagination metadata for the current search result.")}),oyA=I.object({messages:I.array(I.object({id:I.string().uuid(),threadId:I.string().uuid(),threadTitle:I.string(),role:I.enum(["user","assistant"]),content:I.string(),createdAt:I.string().datetime(),updatedAt:I.string().datetime(),highlights:I.array(I.string()),score:I.number().optional()})),pagination:I.object({page:I.number(),limit:I.number(),totalResults:I.number(),totalPages:I.number()}).describe("Page-based pagination metadata for the current search result.")}),Xe=L({operationId:"search.threads",description:"Search threads within one project.",backend:"api",route:{method:"GET",path:"/search/threads",tags:["Search"]},input:nyA,output:QyA,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}}}]}),He=L({operationId:"search.messages",description:"Search messages within one project.",backend:"api",route:{method:"GET",path:"/search/messages",tags:["Search"]},input:iyA,output:oyA,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}}}]}),hqA={threads:Xe.contract,messages:He.contract}});var IyA;var ByA=D(()=>{IyA=["onboarding","setup"]});var hyA,eyA,CyA,cyA,Ly;var Zz=D(()=>{ByA();TA();jA();hyA=I.enum(IyA),eyA=I.object({id:I.string().describe("Unique task identifier (e.g. install_github_app)."),label:I.string().describe("Short human-readable task name."),description:I.string().describe("Explanation of what needs to be completed to satisfy this task."),instructions:I.string().describe("Step-by-step instructions for completing this task."),completed:I.boolean().describe("Whether the task has been completed."),completedAt:I.string().datetime().nullable().describe("ISO 8601 timestamp of when the task was completed, or null."),category:hyA.describe("Task category: onboarding (core setup steps) or setup (additional configuration).")}),CyA=I.object({projectId:I.string().uuid().optional().describe("Project to list tasks for. Auto-filled from CLI and SDK context when omitted.")}),cyA=I.object({tasks:I.array(eyA).describe("All onboarding and setup tasks with their current completion status.")}),Ly=L({operationId:"tasks.list",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.",backend:"api",route:{method:"GET",path:"/tasks",tags:["Tasks"]},input:CyA,output:cyA,pagination:"none",async:"sync"})});var eqA,CqA,XI,cqA,EqA,yqA,DqA,wqA,aqA,rqA,bqA,NqA,uqA,UqA,FqA,LqA,SqA,Wz,Vz,Xz,Hz,Kz,jz,_z,x4t;var EyA=D(()=>{TA();jA();eqA=I.object({id:I.string().uuid().describe("Team ID."),name:I.string().describe("Team name, unique among the org's active teams."),description:I.string().nullable().describe("Optional team description."),createdAt:I.string().datetime().describe("When the team was created."),memberCount:I.number().int().nonnegative().describe("Number of active members in the team.")}),CqA=I.object({userId:I.string().min(1).describe("User ID of the team member."),name:I.string().nullable().describe("Display name for the member, when available."),email:I.string().email().describe("Email address for the member."),addedAt:I.string().datetime().describe("When the member was added to the team.")}),XI=I.string().min(1).optional().describe("Organization to operate on. Auto-filled from CLI and SDK context when omitted."),cqA=I.object({organizationId:XI}),EqA=I.object({teams:I.array(eqA).describe("Active teams in the organization.")}),yqA=I.object({organizationId:XI,name:I.string().trim().min(1).describe("Team name."),description:I.string().trim().min(1).optional().describe("Optional team description.")}),DqA=I.object({id:I.string().uuid().describe("ID of the created team.")}),wqA=I.object({organizationId:XI,teamId:I.string().uuid().describe("Team to update."),name:I.string().trim().min(1).optional().describe("New team name."),description:I.string().trim().min(1).nullable().optional().describe("New team description; null clears it.")}),aqA=I.object({id:I.string().uuid().describe("ID of the updated team.")}),rqA=I.object({params:I.object({teamId:I.string().uuid().describe("Team to delete.")}),query:I.object({organizationId:XI})}).transform(({params:A,query:t})=>({...t,...A})),bqA=I.object({success:I.literal(!0).describe("The team and its memberships were removed.")}),NqA=I.object({organizationId:XI,teamId:I.string().uuid().describe("Team to add the member to."),userId:I.string().min(1).describe("User ID of an active organization member to add.")}),uqA=I.object({id:I.string().uuid().describe("ID of the team membership.")}),UqA=I.object({params:I.object({teamId:I.string().uuid().describe("Team to remove the member from."),userId:I.string().min(1).describe("User ID of the member to remove.")}),query:I.object({organizationId:XI})}).transform(({params:A,query:t})=>({...t,...A})),FqA=I.object({success:I.literal(!0).describe("The membership was removed.")}),LqA=I.object({organizationId:XI,teamId:I.string().uuid().describe("Team to list members for.")}),SqA=I.object({members:I.array(CqA).describe("Active members of the team.")}),Wz=L({operationId:"teams.list",description:"List teams in an organization.",backend:"api",route:{method:"GET",path:"/teams",tags:["Teams"]},input:cqA,output:EqA,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}]}}]}),Vz=L({operationId:"teams.create",description:"Create a team in an organization.",backend:"api",route:{method:"POST",path:"/teams",tags:["Teams"],successStatus:201},input:yqA,output:DqA,pagination:"none",async:"sync"}),Xz=L({operationId:"teams.update",description:"Rename a team or update its description.",backend:"api",route:{method:"PATCH",path:"/teams/{teamId}",tags:["Teams"]},input:wqA,output:aqA,pagination:"none",async:"sync"}),Hz=L({operationId:"teams.delete",description:"Delete a team, its memberships, and its component-ownership assignments.",backend:"api",route:{method:"DELETE",path:"/teams/{teamId}",tags:["Teams"],inputStructure:"detailed"},input:rqA,output:bqA,pagination:"none",async:"sync"}),Kz=L({operationId:"teams.addMember",description:"Add an active organization member to a team.",backend:"api",route:{method:"POST",path:"/teams/{teamId}/members",tags:["Teams"],successStatus:201},input:NqA,output:uqA,pagination:"none",async:"sync"}),jz=L({operationId:"teams.removeMember",description:"Remove a member from a team.",backend:"api",route:{method:"DELETE",path:"/teams/{teamId}/members/{userId}",tags:["Teams"],inputStructure:"detailed"},input:UqA,output:FqA,pagination:"none",async:"sync"}),_z=L({operationId:"teams.listMembers",description:"List a team's active members.",backend:"api",route:{method:"GET",path:"/teams/{teamId}/members",tags:["Teams"]},input:LqA,output:SqA,pagination:"none",async:"sync"}),x4t={list:Wz.contract,create:Vz.contract,update:Xz.contract,delete:Hz.contract,addMember:Kz.contract,removeMember:jz.contract,listMembers:_z.contract}});var lqA,MqA,YqA,mz,$qA,kqA,xz,GqA,JqA,qz,s4t;var yyA=D(()=>{TA();jA();lqA=I.object({kind:I.enum(["user","workspace"]),name:I.string().optional(),email:I.string().optional()}),MqA=I.object({container:I.string().min(1).describe("The container to create the work item in: its id, short key (e.g. a Linear team key like ENG), or display name."),title:I.string().min(1),bodyMarkdown:I.string().optional(),state:I.string().optional(),itemType:I.string().optional(),organizationId:I.string().min(1).optional().describe("Optional organization ID to scope the request to. User credentials must belong to it; a secret key may only reference its own organization. Defaults to the credential's active organization."),clientRequestId:I.string().min(1).optional().describe("Optional caller-supplied idempotency key. When provided, retrying the same logical create with the same clientRequestId reuses the original result instead of creating a duplicate external work item.")}).strict(),YqA=I.object({identifier:I.string(),title:I.string(),url:I.string(),state:I.string(),attribution:lqA.optional(),reused:I.boolean()}),mz=L({operationId:"work-items.create",description:"Create a work item (e.g. a Linear issue) in a connected issue tracker, attributing the write to the requesting user.",backend:"api",route:{method:"POST",path:"/work-items",tags:["Work Items"],successStatus:201},input:MqA,output:YqA,pagination:"none",async:"sync"}),$qA=I.object({itemId:I.string().min(1).describe("The work item to comment on."),bodyMarkdown:I.string().min(1),organizationId:I.string().min(1).optional().describe("Optional organization ID to scope the request to. User credentials must belong to it; a secret key may only reference its own organization. Defaults to the credential's active organization.")}).strict(),kqA=I.object({identifier:I.string(),url:I.string()}),xz=L({operationId:"work-items.comment",description:"Add a comment to an existing work item.",backend:"api",route:{method:"POST",path:"/work-items/{itemId}/comment",tags:["Work Items"]},input:$qA,output:kqA,pagination:"none",async:"sync"}),GqA=I.object({itemId:I.string().min(1).describe("The work item to transition."),state:I.string().min(1).describe("The target workflow state."),organizationId:I.string().min(1).optional().describe("Optional organization ID to scope the request to. User credentials must belong to it; a secret key may only reference its own organization. Defaults to the credential's active organization.")}).strict(),JqA=I.object({identifier:I.string(),title:I.string(),url:I.string(),state:I.string(),changed:I.boolean()}),qz=L({operationId:"work-items.transition",description:"Move a work item to a target workflow state.",backend:"api",route:{method:"POST",path:"/work-items/{itemId}/transition",tags:["Work Items"]},input:GqA,output:JqA,pagination:"none",async:"sync"}),s4t={create:mz.contract,comment:xz.contract,transition:qz.contract}});var dz;var DyA=D(()=>{zW();XW();gY();BY();cV();WY();HY();dV();ja();$_();Nk();Nf();tN();hcA();Jf();PcA();hEA();yEA();DEA();wEA();Lz();$EA();lz();Yz();iN();kz();gyA();vz();Zz();EyA();xf();yyA();dz={me:uf.contract,automations:{list:eY.contract,get:CY.contract,create:cY.contract,update:EY.contract,enable:yY.contract,disable:DY.contract,runs:{list:wY.contract,get:aY.contract,logs:rY.contract}},logs:{query:dB.contract,schema:pB.contract,volume:sB.contract,patterns:Ah.contract,nativeQuery:th.contract},logSources:{listProviders:Va.contract,list:xB.contract,create:qB.contract,get:Xa.contract,update:Ha.contract,delete:Ka.contract},logStreams:{list:Ek.contract,create:yk.contract,get:Dk.contract,update:wk.contract,delete:ak.contract,reassign:rk.contract},connectedAccounts:{beginConnect:iY.contract,getConnectAttempt:QY.contract,list:oY.contract,disconnect:IY.contract},integrations:{listProviders:KW.contract,listConnections:jW.contract,getConnection:_W.contract,createConnection:mW.contract,beginConnect:xW.contract,getConnectAttempt:qW.contract,disconnectConnection:dW.contract,updateConnectionCredentials:pW.contract,getOrganizationExternalIdentityJitPolicy:tV.contract,updateOrganizationExternalIdentityJitPolicy:gV.contract,getConnectionExternalIdentityJitPolicy:nV.contract,updateConnectionExternalIdentityJitPolicy:iV.contract,getSlackConfiguration:oV.contract,updateSlackConfiguration:IV.contract,listSlackChannelProjectMappings:hV.contract,setSlackChannelProjectMapping:eV.contract,deleteSlackChannelProjectMapping:CV.contract},notificationChannels:{getProject:gz.contract},notificationDeliveryRules:{list:hz.contract,options:ez.contract,create:Cz.contract,update:cz.contract,delete:Ez.contract},mcpConnectors:{listProviders:AN.contract,list:Ne.contract,get:ue.contract,details:Ue.contract,search:Fe.contract,describe:Le.contract,call:Se.contract,create:le.contract,update:Me.contract,disconnect:Ye.contract,setReadOnly:$e.contract,beginOAuthInstall:ke.contract,getOAuthInstallAttempt:Ge.contract},sandboxPresets:{deletePreset:We.contract,listConnections:ve.contract,listTypes:wN.contract,testPreset:Ve.contract,upsertPreset:Ze.contract},scripts:{list:Tz.contract,get:Rz.contract,create:Pz.contract,update:fz.contract,delete:zz.contract},logMatchExpressions:{list:_Y.contract,get:mY.contract,create:xY.contract,update:qY.contract,disable:dY.contract},memory:{put:Je.contract,get:Te.contract,list:Re.contract,search:Pe.contract,delete:fe.contract},onboarding:{getState:Dz.contract,skipIntegration:wz.contract,skipGithubAppInstallation:az.contract,skipSampleIssue:rz.contract,finish:bz.contract},organizations:{list:uz.contract,get:Uz.contract,create:Nz.contract,update:Fz.contract},members:{list:Uf.contract,updateRole:Ff.contract,remove:Lf.contract,invite:Sf.contract,listInvitations:lf.contract,revokeInvitation:Mf.contract},teams:{list:Wz.contract,create:Vz.contract,update:Xz.contract,delete:Hz.contract,addMember:Kz.contract,removeMember:jz.contract,listMembers:_z.contract},publicKeys:{list:XB.contract,get:HB.contract,ensureLogForwarding:KB.contract,update:jB.contract,deactivate:_B.contract},secretKeys:{list:Ta.contract,get:Ra.contract,create:Pa.contract,update:fa.contract,delete:za.contract},projects:{list:CN.contract,get:cN.contract,create:EN.contract,update:yN.contract,delete:DN.contract},search:{threads:Xe.contract,messages:He.contract},messages:{list:TcA.contract,append:RcA.contract},threads:{list:Of.contract,get:vf.contract,getStatus:Zf.contract,stop:Wf.contract,create:Vf.contract,update:Xf.contract,fork:Hf.contract,setVisibility:Kf.contract,createShareLink:jf.contract,listShareLinks:_f.contract,revokeShareLink:mf.contract},runs:{list:Tf.contract,listForThread:Rf.contract,get:Pf.contract,cancel:ff.contract},pullRequests:{list:Sz.contract},issues:{count:Ua.contract,create:VB.contract,list:Na.contract,search:ua.contract,get:Fa.contract,resolve:La.contract,ignore:Sa.contract,reopen:la.contract,reassignAndReopen:Ma.contract,mute:Ya.contract,unmute:$a.contract},workItems:{create:mz.contract,comment:xz.contract,transition:qz.contract},billing:{getSummary:NY.contract,getUsage:uY.contract,listTransactions:UY.contract,getAutoTopUp:SY.contract,updateAutoTopUp:lY.contract,purchaseCredits:MY.contract,listPlans:YY.contract,previewPlanChange:$Y.contract,previewSubscriptionCancellation:PY.contract,scheduleSubscriptionCancellation:fY.contract,resumeSubscriptionCancellation:zY.contract,changePlan:kY.contract,createCheckoutSession:GY.contract,getCheckoutSessionStatus:JY.contract,createPortalSession:TY.contract,getPaymentMethod:RY.contract},tasks:{list:Ly.contract},recommendations:{list:Ny.contract},repos:{list:uy.contract,add:Uy.contract,remove:Fy.contract},components:{list:pw.contract,get:sw.contract,register:ZB.contract,deregister:Aa.contract,rename:ta.contract,assignTeam:ga.contract,retirementPreview:na.contract,retire:ia.contract,restorationPreview:Qa.contract,restore:oa.contract,mergePreview:ca.contract,merge:Ea.contract,relationships:{list:Ia.contract,preview:Ba.contract,add:ha.contract,remove:ea.contract},incidents:{list:ya.contract},timeline:Da.contract}}});var HI=D(()=>{lZ();gY();BY();DyA();WY();HY();ja();Nk();Nf();Jf();Lz();lz();Yz();kz();vz();Zz()});var TqA="https://api.sazabi.com",RqA="x-sazabi-client-source",ayA=(A)=>{return{streamRun:async(t)=>{return wyA({options:A,path:`/runs/${encodeURIComponent(t.runId)}/stream`,cursor:t.cursor,signal:t.signal})},streamThread:async(t)=>{return wyA({options:A,path:`/threads/${encodeURIComponent(t.threadId)}/stream`,cursor:t.cursor,signal:t.signal})}}},wyA=async(A)=>{let t=A.options.fetch??globalThis.fetch;if(!t)throw Error("Fetch transport is not available in this runtime.");let g=await A.options.credentialProvider.getToken(),i=PqA(A.options.apiBaseUrl,A.path,A.cursor);return zqA({url:i,token:g,clientSource:A.options.clientSource,initialCursor:A.cursor,signal:A.signal,fetch:t})},PqA=(A,t,g)=>{let i=fqA(A??TqA),n=new URL(`${i}${t}`);if(g)n.searchParams.set(WM,g);return n.toString()},fqA=(A)=>{let t=A.replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`},zqA=async(A)=>{let t=[],g=[],i=!1,n=!1,Q,o=A.initialCursor,B=new AbortController,h=(a)=>{if(i)return;i=!0,Q=a;while(g.length>0)g.shift()?.({value:void 0,done:!0})},e=(a)=>{let u=g.shift();if(u){u({value:a,done:!1});return}t.push(a)},C=(a)=>{if(a.event===XM){let F=VqA(a.data);if(F!==void 0)o=F;return}if(a.data===HM){n=!0,B.abort(),h();return}let u=XqA(a.data);if(u)e(u)},c=()=>{n=!0,B.abort(),h()};if(A.signal)if(A.signal.aborted)n=!0,B.abort();else A.signal.addEventListener("abort",c,{once:!0});let E={[Symbol.asyncIterator](){return E},get cursor(){return o},next:async()=>{if(t.length>0)return{value:t.shift(),done:!1};if(i){if(Q)throw Q;return{value:void 0,done:!0}}return new Promise((a)=>{g.push(a)}).then((a)=>{if(a.done&&Q)throw Q;return a})},return:async()=>{return n=!0,B.abort(),h(),{value:void 0,done:!0}},throw:async(a)=>{throw n=!0,B.abort(),h(a instanceof Error?a:Error(String(a))),a},close:async()=>{n=!0,B.abort(),h()}};if(n)return h(),E;let y=await A.fetch(A.url,{method:VM,headers:OqA(A.token,A.clientSource),signal:B.signal});if(await vqA(y))h();else ZqA(y,C).then(()=>h()).catch((a)=>{if(KqA(a)||n||A.signal?.aborted){h();return}h(jqA(a))});return E},OqA=(A,t)=>{return{accept:"text/event-stream",authorization:`Bearer ${A}`,...t?{[RqA]:t}:{}}},vqA=async(A)=>{if(A.status===204)return!0;if(A.ok&&A.body)return!1;let t=await HqA(A);if(A.status===401)throw Error("Authentication failed. Check your credential.");if(A.status===403)throw Error(`Forbidden (403): ${t||"Credential may not have access to this resource"}`);if(A.status===404)throw Error(`Not found (404): ${t||"Run or thread not found"}`);if(A.status===400)throw Error(`Invalid stream cursor (400): ${t||"The provided cursor was rejected"}`);if(A.status>=400&&A.status<500&&A.status!==429)throw Error(`Client error (${A.status}): ${t}`);if(!A.body)throw Error("Agent stream response did not include a body.");throw Error(A.status===429?`Rate limited (429): ${t}`:`Server error (${A.status}): ${t}`)},ZqA=async(A,t)=>{let g=A.body?.getReader();if(!g)throw Error("Agent stream response did not include a body.");let i=new TextDecoder,n="",Q=WqA(t);try{while(!0){let o=await g.read();if(o.done)break;n+=i.decode(o.value,{stream:!0});let B=n.split(/\r\n|\r|\n/);n=B.pop()??"";for(let h of B)Q.line(h)}if(n+=i.decode(),n)for(let o of n.split(/\r\n|\r|\n/))Q.line(o);Q.flush()}finally{g.releaseLock()}},WqA=(A)=>{let t="message",g=[],i=()=>{t="message",g=[]},n=()=>{if(g.length===0){i();return}A({event:t,data:g.join(`
|
|
8708
8708
|
`)}),i()};return{line:(Q)=>{if(Q===""){n();return}if(Q.startsWith(":"))return;let o=Q.indexOf(":"),B=o===-1?Q:Q.slice(0,o),h=o===-1?"":Q.slice(o+1),e=h.startsWith(" ")?h.slice(1):h;if(B==="event"){t=e||"message";return}if(B==="data")g.push(e)},flush:n}},VqA=(A)=>{try{let t=ZM.safeParse(JSON.parse(A));return t.success?t.data.streamNextOffset:void 0}catch{return}},XqA=(A)=>{try{let t=vM.safeParse(JSON.parse(A));return t.success?t.data:void 0}catch{return}},HqA=async(A)=>{try{return await A.text()}catch{return""}},KqA=(A)=>{return A instanceof Error&&A.name==="AbortError"},jqA=(A)=>{return A instanceof Error?A:Error(String(A))};var ryA=D(()=>{HI()});var pz,sz,AO,byA;var NyA=D(()=>{TA();pz=I.object({severities:I.array(I.string()).optional().describe("Limit results to the listed severities."),services:I.array(I.string()).optional().describe("Limit results to the listed service names."),environments:I.array(I.string()).optional().describe("Limit results to the listed deployment environments."),searchTerm:I.string().optional().describe("Case-insensitive substring match against the log body."),traceId:I.string().optional().describe("Limit results to one trace ID."),attributes:I.record(I.string(),I.string()).optional().describe("Limit results to logs whose attributes contain every listed key with an exactly equal value.")}),sz=I.object({service:I.string(),namespace:I.string(),environment:I.string(),host:I.string(),container:I.string(),pod:I.string()}),AO=I.object({id:I.string(),timestamp:I.string().datetime(),severity:I.string(),body:I.string(),service:I.string(),traceId:I.string(),spanId:I.string(),attributes:I.record(I.string(),I.string()),resource:sz}),byA=I.object({type:I.literal("logs"),timestamp:I.string().datetime(),data:I.array(AO)})});var _qA="https://{region}.intake.sazabi.com",mqA="https://{region}.tail.sazabi.com",FyA=500,xqA=5000,LyA="sazabi.public_key",qqA="x-sazabi-internal-log-forwarding-secret",dqA="x-sazabi-internal-log-forwarding-source",pqA=(A)=>{return A.startsWith("[")&&A.endsWith("]")?A.slice(1,-1):A},SyA=(A)=>{let t=pqA(A);return t==="localhost"||t==="127.0.0.1"||t==="::1"},sqA,AdA,tdA,lyA=(A)=>{let t=new Map;return{tail:async(g)=>{let i=await EdA(A.credentialProvider,g.projectId,"logs.tail"),n=await ydA(A,t,i,g.region,"logs.tail"),Q=idA({projectId:i,region:n,filters:g.filters,apiBaseUrl:A.apiBaseUrl,tailBaseUrl:A.tailBaseUrl}),o=await A.credentialProvider.getToken(),B=A.fetch??globalThis.fetch;if(!B)throw Error("Fetch transport is not available in this runtime.");return wdA({token:o,url:Q,signal:g.signal,fetch:B})},forward:async(g)=>{let i=await DdA(A,t,g.projectId??await A.credentialProvider.getProjectId?.(),g.region,"logs.forward"),n=BdA(i,A.intakeBaseUrl),Q=A.fetch??globalThis.fetch,o=edA(g.logs,g.publicKey),B=LdA(o);return await FdA(Q,n,o,cdA(g.sazabiInternalForwarding)),{forwardedCount:B,failedCount:0}}}},gdA="3010",ndA,idA=(A)=>{let t=(A.tailBaseUrl??QdA({region:A.region,apiBaseUrl:A.apiBaseUrl})).replace("{region}",A.region),g=odA(t);g.searchParams.set("projectId",A.projectId);let i=IdA(A.filters);if(i)g.searchParams.set("filters",i);return g.toString()},QdA=(A)=>{if(A.apiBaseUrl)try{let t=new URL(A.apiBaseUrl).hostname;if(t.endsWith(".sazabi.dev")){let g=t.includes(".staging.")?"staging.sazabi.dev":"development.sazabi.dev";return`https://${A.region}.tail.${g}`}}catch{}return mqA.replace("{region}",A.region)},odA=(A)=>{let t=(()=>{try{return new URL(A)}catch{return null}})();if(!t)throw Error(`Invalid tail base URL: ${A}`);if(SyA(t.hostname)){if(t.protocol="http:",!t.port||ndA.has(t.port))t.port=gdA;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},IdA=(A)=>{if(!A)return;let t=Object.entries(A).filter(([,g])=>g!==void 0&&(!Array.isArray(g)||g.length>0)&&(typeof g!=="object"||Array.isArray(g)||g===null||Object.keys(g).length>0)&&g!=="");if(t.length===0)return;return JSON.stringify(Object.fromEntries(t))},BdA=(A,t)=>{let g=(t??_qA).replace("{region}",A),i=g.endsWith("/")?g.slice(0,-1):g,n=hdA(i);if(n)return n;let Q=i.match(/^https:\/\/([a-z0-9-]+)\.intake\.([a-z0-9.]+)$/);return`${Q?`https://otlp.${Q[1]}.intake.${Q[2]}`:i}/v1/logs`},hdA=(A)=>{let t=(()=>{try{return new URL(A)}catch{return null}})();if(!t)return;if(!SyA(t.hostname))return;return t.pathname="/adapters/otlp",t.toString()},edA=(A,t)=>{let g=A.resourceLogs;if(!g||g.length===0)return{...A,resourceLogs:[{resource:{attributes:[MyA(t)]},scopeLogs:[]}]};return{...A,resourceLogs:g.map((i)=>({...i,resource:{...i.resource,attributes:CdA(i.resource?.attributes,t)}}))}},CdA=(A,t)=>{return[...(A??[]).filter((i)=>i?.key!==LyA),MyA(t)]},MyA=(A)=>({key:LyA,value:{stringValue:A}}),cdA=(A)=>{if(!A?.secret)return{};return{[qqA]:A.secret,...A.source?{[dqA]:A.source}:{}}},EdA=async(A,t,g)=>{let i=t??await A.getProjectId?.();if(i)return i;throw kyA(g,"Project ID is required",["projectId"])},ydA=async(A,t,g,i,n)=>{return i??await YyA(A,t,g)},DdA=async(A,t,g,i,n)=>{if(i)return i;if(!g)throw kyA(n,"Project ID is required",["projectId"]);return YyA(A,t,g)},YyA=async(A,t,g)=>{let i=t.get(g);if(i)return i;let n=A.raw.projects.get({projectId:g}).then((Q)=>Q.project.region);t.set(g,n);try{return await n}catch(Q){throw t.delete(g),Q}},wdA=async(A)=>{let t=[],g=[],i=!1,n=!1,Q,o=0,B,h,e=(u)=>{if(i)return;i=!0,Q=u;while(g.length>0){let F=g.shift();if(F)F({value:void 0,done:!0})}},C=(u)=>{let F=g.shift();if(F){F({value:u,done:!1});return}t.push(u)},c=()=>{h?.abort()},E=(u)=>{if(u.event!=="log"){if(u.id)B=u.id;return}let F=udA(u.data);for(let Y of F)C(Y);if(u.id)B=u.id},y=async(u)=>{let F=!1;while(!i&&!n){let Y=new AbortController,J=()=>Y.abort();h=Y;let m=!1;A.signal?.addEventListener("abort",J,{once:!0});try{let v=await A.fetch(adA(A.url,B),{method:"GET",headers:{accept:"text/event-stream",authorization:`Bearer ${A.token}`},signal:Y.signal});await rdA(v),o=0,F=!0,u(),await bdA(v,E),m=!0}catch(v){if(UyA(v)||A.signal?.aborted)break;let BA=uyA(v);if(!F||UdA(BA))throw BA;m=!0}finally{if(A.signal?.removeEventListener("abort",J),h===Y)h=void 0}if(i||n||A.signal?.aborted)break;if(!m)continue;o+=1,await $yA(Math.min(FyA*2**(o-1),xqA),A.signal)}};if(A.signal?.addEventListener("abort",()=>{n=!0,c(),e()},{once:!0}),A.signal?.aborted)n=!0,c(),e();await new Promise((u,F)=>{let Y=!1;y(()=>{if(!Y)Y=!0,u()}).catch((m)=>{let v=uyA(m);if(!Y){Y=!0,F(v);return}if(!UyA(m))e(v)})});let a={[Symbol.asyncIterator](){return a},next:async()=>{if(t.length>0)return{value:t.shift(),done:!1};if(i){if(Q)throw Q;return{value:void 0,done:!0}}return new Promise((u)=>{g.push(u)}).then((u)=>{if(u.done&&Q)throw Q;return u})},return:async()=>{return n=!0,c(),e(),{value:void 0,done:!0}},throw:async(u)=>{throw n=!0,c(),e(u instanceof Error?u:Error(String(u))),u}};return a},adA=(A,t)=>{if(!t)return A;let g=new URL(A);return g.searchParams.set("cursor",t),g.toString()},rdA=async(A)=>{if(A.ok&&A.body)return;let t=await A.text();if(A.status===401)throw Error("Authentication failed. Check your credential.");if(A.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(A.status>=400&&A.status<500&&A.status!==429)throw Error(`Client error (${A.status}): ${t}`);if(!A.body)throw Error("Tail stream response did not include a body.");throw Error(A.status===429?`Rate limited (429): ${t}`:`Server error (${A.status}): ${t}`)},bdA=async(A,t)=>{let g=A.body?.getReader();if(!g)throw Error("Tail stream response did not include a body.");let i=new TextDecoder,n="",Q=NdA(t);try{while(!0){let o=await g.read();if(o.done)break;n+=i.decode(o.value,{stream:!0});let B=n.split(/\r\n|\r|\n/);n=B.pop()??"";for(let h of B)Q.line(h)}if(n+=i.decode(),n){let o=n.split(/\r\n|\r|\n/);for(let B of o)Q.line(B)}Q.flush()}finally{g.releaseLock()}},NdA=(A)=>{let t="message",g,i=[],n=()=>{t="message",g=void 0,i=[]},Q=()=>{if(i.length===0&&!g){n();return}A({event:t,data:i.join(`
|
|
8709
|
-
`),...g?{id:g}:{}}),n()};return{line:(o)=>{if(o===""){Q();return}if(o.startsWith(":"))return;let B=o.indexOf(":"),h=B===-1?o:o.slice(0,B),e=B===-1?"":o.slice(B+1),C=e.startsWith(" ")?e.slice(1):e;if(h==="event"){t=C||"message";return}if(h==="data"){i.push(C);return}if(h==="id"&&!C.includes("\x00"))g=C},flush:Q}},udA=(A)=>{try{let t=byA.safeParse(JSON.parse(A));if(!t.success)return[];return t.data.data}catch{return[]}},uyA=(A)=>{return A instanceof Error?A:Error(String(A))},UyA=(A)=>{return A instanceof Error&&A.name==="AbortError"},UdA=(A)=>{return A.message.startsWith("Authentication failed")||A.message.startsWith("Forbidden (")||A.message.startsWith("Wrong region (")||A.message.startsWith("Client error (")},FdA=async(A,t,g,i={},n=3,Q=1e4)=>{let o;for(let B=0;B<=n;B+=1){let h=new AbortController,e=globalThis.setTimeout(()=>h.abort(),Q);try{let C=await A(t,{method:"POST",headers:{"content-type":"application/json",...i},body:JSON.stringify(g),signal:h.signal});if(C.ok)return;let c=await C.text();if(C.status===401||C.status===403)throw Error("Authentication failed. Check your public key.");if(C.status>=400&&C.status<500&&C.status!==429)throw Error(`Client error (${C.status}): ${c}`);o=Error(C.status===429?`Rate limited (429): ${c}`:`Server error (${C.status}): ${c}`)}catch(C){let c=C instanceof Error?C.message:String(C);if(c.startsWith("Authentication failed")||c.startsWith("Client error ("))throw C instanceof Error?C:Error(c);o=C instanceof Error&&C.name==="AbortError"?Error("Request timed out"):C instanceof Error?C:Error(String(C))}finally{globalThis.clearTimeout(e)}if(B<n)await $yA(FyA*2**B)}throw Error(`Failed after ${n+1} attempts: ${o?.message??"Unknown error"}`)},LdA=(A)=>{return A.resourceLogs?.reduce((t,g)=>t+(g.scopeLogs?.reduce((i,n)=>i+(n.logRecords?.length??0),0)??0),0)??0},$yA=async(A,t)=>{if(t?.aborted)return;await new Promise((g)=>{let i=globalThis.setTimeout(g,A);t?.addEventListener("abort",()=>{globalThis.clearTimeout(i),g()},{once:!0})})},kyA=(A,t,g)=>{return new dt("BAD_REQUEST",{message:t,data:{operationId:A,missingContext:g}})};var tO=D(()=>{BB();NyA();TA();sqA=I.object({projectId:I.string().uuid().optional().describe("Project to tail logs for. Auto-filled from CLI and SDK context when omitted."),filters:pz.optional().describe("Optional filters applied by the tail SSE service.")}),AdA=I.object({publicKey:I.string().min(1).describe("Public key for intake auth. Create or list one via the public key endpoints."),logs:I.custom((A)=>typeof A==="object"&&A!==null).describe("OTLP logs export request payload to send to the intake service.")}),tdA=I.object({forwardedCount:I.number().int().nonnegative().describe("Number of log records accepted by the intake request."),failedCount:I.number().int().nonnegative().describe("Number of log records rejected by the intake request.")}),ndA=new Set(["15006","3010"])});var gO="https://api.sazabi.com",JyA="https://api.platform.sazabi.com",TyA="sazabi-cli",SdA="urn:ietf:params:oauth:grant-type:device_code",RyA=(A)=>{let t=$u(new Vu(dz,{url:ldA(A.apiBaseUrl??gO),headers:async()=>{let n=new Headers({authorization:`Bearer ${await A.credentialProvider.getToken()}`});if(A.clientSource)n.set("x-sazabi-client-source",A.clientSource);if(A.sandboxActorDescriptor)n.set("x-sazabi-sandbox-actor",A.sandboxActorDescriptor);return n},fetch:A.fetch,customErrorResponseBodyDecoder:(n,Q)=>{let o=RdA(n);if(!o)return null;return new dt(o.code,{message:o.message,status:Q.status,data:{operationId:o.operationId,missingContext:o.missingContext,...o.reason!==void 0?{reason:o.reason}:{}}})}})),g=lyA({raw:t,credentialProvider:A.credentialProvider,fetch:A.fetch,apiBaseUrl:A.apiBaseUrl??gO,intakeBaseUrl:A.intakeBaseUrl,tailBaseUrl:A.tailBaseUrl}),i=ayA({credentialProvider:A.credentialProvider,fetch:A.fetch,apiBaseUrl:A.apiBaseUrl??gO,clientSource:A.clientSource});return{raw:t,me:async()=>t.me({}),automations:{list:async(n={})=>t.automations.list(await gA(A.credentialProvider,n,"automations.list")),get:async(n)=>t.automations.get(await gA(A.credentialProvider,n,"automations.get")),create:async(n)=>t.automations.create(await gA(A.credentialProvider,n,"automations.create")),update:async(n)=>t.automations.update(await gA(A.credentialProvider,n,"automations.update")),enable:async(n)=>t.automations.enable(await gA(A.credentialProvider,n,"automations.enable")),disable:async(n)=>t.automations.disable(await gA(A.credentialProvider,n,"automations.disable")),runs:{list:async(n)=>t.automations.runs.list(await gA(A.credentialProvider,n,"automations.runs.list")),get:async(n)=>t.automations.runs.get(await gA(A.credentialProvider,n,"automations.runs.get")),logs:async(n)=>t.automations.runs.logs(await gA(A.credentialProvider,n,"automations.runs.logs"))}},logs:{...g,query:async(n={})=>t.logs.query(await gA(A.credentialProvider,n,dB.operationId)),schema:async(n={})=>t.logs.schema(await gA(A.credentialProvider,n,pB.operationId)),volume:async(n)=>t.logs.volume(await gA(A.credentialProvider,n,sB.operationId)),patterns:async(n={})=>t.logs.patterns(await gA(A.credentialProvider,n,Ah.operationId)),nativeQuery:async(n)=>t.logs.nativeQuery(await gA(A.credentialProvider,n,th.operationId))},onboarding:{getState:async(n={})=>t.onboarding.getState(await $dA(A.credentialProvider,n)),skipSampleIssue:async()=>t.onboarding.skipSampleIssue({}),finish:async(n)=>t.onboarding.finish(n)},organizations:{list:async()=>t.organizations.list({}),get:async(n)=>t.organizations.get(n),create:async(n)=>t.organizations.create(n),update:async(n)=>t.organizations.update(await YdA(A.credentialProvider,n))},members:{list:async(n={})=>t.members.list(await kA(A.credentialProvider,n)),updateRole:async(n)=>t.members.updateRole(await kA(A.credentialProvider,n)),remove:async(n)=>{let Q=await kA(A.credentialProvider,n);return t.members.remove({params:{member:Q.member},query:{organizationId:Q.organizationId}})},invite:async(n)=>t.members.invite(await kA(A.credentialProvider,n)),listInvitations:async(n={})=>t.members.listInvitations(await kA(A.credentialProvider,n)),revokeInvitation:async(n)=>{let Q=await kA(A.credentialProvider,n);return t.members.revokeInvitation({params:{invitationId:Q.invitationId},query:{organizationId:Q.organizationId}})}},teams:{list:async(n={})=>t.teams.list(await kA(A.credentialProvider,n)),create:async(n)=>t.teams.create(await kA(A.credentialProvider,n)),update:async(n)=>t.teams.update(await kA(A.credentialProvider,n)),delete:async(n)=>{let Q=await kA(A.credentialProvider,n);return t.teams.delete({params:{teamId:Q.teamId},query:{organizationId:Q.organizationId}})},addMember:async(n)=>t.teams.addMember(await kA(A.credentialProvider,n)),removeMember:async(n)=>{let Q=await kA(A.credentialProvider,n);return t.teams.removeMember({params:{teamId:Q.teamId,userId:Q.userId},query:{organizationId:Q.organizationId}})},listMembers:async(n)=>t.teams.listMembers(await kA(A.credentialProvider,n))},publicKeys:{list:async(n={})=>t.publicKeys.list(await gA(A.credentialProvider,n,XB.operationId)),get:async(n)=>t.publicKeys.get(await gA(A.credentialProvider,n,HB.operationId)),ensureLogForwarding:async(n={})=>t.publicKeys.ensureLogForwarding(await gA(A.credentialProvider,n,KB.operationId)),update:async(n)=>t.publicKeys.update(await gA(A.credentialProvider,n,jB.operationId)),deactivate:async(n)=>{let Q=await gA(A.credentialProvider,n,_B.operationId);return t.publicKeys.deactivate({params:{keyId:Q.keyId},query:{projectId:Q.projectId}})}},secretKeys:{list:async(n={})=>t.secretKeys.list(n),get:async(n)=>t.secretKeys.get(n),create:async(n)=>t.secretKeys.create(n),update:async(n)=>t.secretKeys.update(n),delete:async(n)=>{await t.secretKeys.delete({params:{keyId:n.keyId}})}},search:{threads:async(n)=>t.search.threads(await gA(A.credentialProvider,n,Xe.operationId)),messages:async(n)=>t.search.messages(await gA(A.credentialProvider,n,He.operationId))},projects:{list:async(n={})=>t.projects.list(await MdA(A.credentialProvider,n)),get:async(n)=>t.projects.get(n),create:async(n)=>t.projects.create(await kA(A.credentialProvider,n))},messages:{list:async(n)=>t.messages.list(n),append:async(n)=>GyA(t,await t.messages.append(TdA(n)))},threads:{list:async(n={})=>t.threads.list(await kdA(A.credentialProvider,n)),get:async(n)=>t.threads.get(n),getStatus:async(n)=>t.threads.getStatus(n),stop:async(n)=>t.threads.stop(n),create:async(n)=>GyA(t,await t.threads.create(await JdA(A.credentialProvider,n))),update:async(n)=>t.threads.update(n),fork:async(n)=>t.threads.fork(n),setVisibility:async(n)=>t.threads.setVisibility(n),createShareLink:async(n)=>t.threads.createShareLink(n),listShareLinks:async(n)=>t.threads.listShareLinks(n),revokeShareLink:async(n)=>t.threads.revokeShareLink(n),stream:async(n)=>i.streamThread(n)},runs:{list:async(n={})=>t.runs.list(await GdA(A.credentialProvider,n)),listForThread:async(n)=>t.runs.listForThread(n),get:async(n)=>t.runs.get(n),cancel:async(n)=>t.runs.cancel(n),stream:async(n)=>i.streamRun(n)},logSources:{listProviders:async()=>t.logSources.listProviders({}),list:async(n={})=>t.logSources.list(await gA(A.credentialProvider,n,xB.operationId)),get:async(n)=>t.logSources.get(n),create:async(n)=>t.logSources.create(await gA(A.credentialProvider,n,qB.operationId)),update:async(n)=>t.logSources.update(n),delete:async(n)=>t.logSources.delete(n)},logStreams:{list:async(n)=>t.logStreams.list(n),get:async(n)=>t.logStreams.get(n),create:async(n)=>t.logStreams.create(n),update:async(n)=>t.logStreams.update(n),delete:async(n)=>t.logStreams.delete(n),reassign:async(n)=>t.logStreams.reassign(n)},connectedAccounts:{beginConnect:async(n)=>t.connectedAccounts.beginConnect(await kA(A.credentialProvider,n)),getConnectAttempt:async(n)=>t.connectedAccounts.getConnectAttempt(await kA(A.credentialProvider,n)),list:async(n={})=>t.connectedAccounts.list(await kA(A.credentialProvider,n)),disconnect:async(n)=>t.connectedAccounts.disconnect(await kA(A.credentialProvider,n))},integrations:{listProviders:async(n={})=>t.integrations.listProviders(await kA(A.credentialProvider,n)),listConnections:async(n={})=>t.integrations.listConnections(await kA(A.credentialProvider,n)),getConnection:async(n)=>t.integrations.getConnection(await kA(A.credentialProvider,n)),createConnection:async(n)=>t.integrations.createConnection(await kA(A.credentialProvider,n)),beginConnect:async(n)=>t.integrations.beginConnect(await kA(A.credentialProvider,n)),getConnectAttempt:async(n)=>t.integrations.getConnectAttempt(await kA(A.credentialProvider,n)),disconnectConnection:async(n)=>t.integrations.disconnectConnection(await kA(A.credentialProvider,n)),updateConnectionCredentials:async(n)=>t.integrations.updateConnectionCredentials(await kA(A.credentialProvider,n))},mcpConnectors:{list:async(n={})=>t.mcpConnectors.list(await gA(A.credentialProvider,n,Ne.operationId)),get:async(n)=>t.mcpConnectors.get(await gA(A.credentialProvider,n,ue.operationId)),details:async(n)=>t.mcpConnectors.details(await gA(A.credentialProvider,n,Ue.operationId)),listProviders:async()=>t.mcpConnectors.listProviders({}),search:async(n={})=>t.mcpConnectors.search(await gA(A.credentialProvider,n,Fe.operationId)),describe:async(n)=>t.mcpConnectors.describe(await gA(A.credentialProvider,n,Le.operationId)),call:async(n)=>t.mcpConnectors.call(await gA(A.credentialProvider,n,Se.operationId)),create:async(n)=>t.mcpConnectors.create(await gA(A.credentialProvider,n,le.operationId)),update:async(n)=>t.mcpConnectors.update(await gA(A.credentialProvider,n,Me.operationId)),disconnect:async(n)=>{await t.mcpConnectors.disconnect(await gA(A.credentialProvider,n,Ye.operationId))},setReadOnly:async(n)=>t.mcpConnectors.setReadOnly(await gA(A.credentialProvider,n,$e.operationId)),beginOAuthInstall:async(n)=>t.mcpConnectors.beginOAuthInstall(await gA(A.credentialProvider,n,ke.operationId)),getOAuthInstallAttempt:async(n)=>t.mcpConnectors.getOAuthInstallAttempt(await gA(A.credentialProvider,n,Ge.operationId))},sandboxPresets:{delete:async(n)=>t.sandboxPresets.deletePreset(await gA(A.credentialProvider,n,We.operationId)),listConnections:async(n={})=>t.sandboxPresets.listConnections(await gA(A.credentialProvider,n,ve.operationId)),listTypes:async()=>t.sandboxPresets.listTypes({}),test:async(n)=>t.sandboxPresets.testPreset(await gA(A.credentialProvider,n,Ve.operationId)),upsert:async(n)=>t.sandboxPresets.upsertPreset(await gA(A.credentialProvider,n,Ze.operationId))},memory:{list:async(n={})=>t.memory.list(await gA(A.credentialProvider,n,Re.operationId)),get:async(n)=>t.memory.get(await gA(A.credentialProvider,n,Te.operationId)),put:async(n)=>t.memory.put(await gA(A.credentialProvider,n,Je.operationId)),search:async(n)=>t.memory.search(await gA(A.credentialProvider,n,Pe.operationId)),delete:async(n)=>t.memory.delete(await gA(A.credentialProvider,n,fe.operationId))},logMatchExpressions:{list:async(n={})=>t.logMatchExpressions.list(await gA(A.credentialProvider,n,"logMatchExpressions.list")),get:async(n)=>t.logMatchExpressions.get(await gA(A.credentialProvider,n,"logMatchExpressions.get")),create:async(n)=>t.logMatchExpressions.create(await gA(A.credentialProvider,n,"logMatchExpressions.create")),update:async(n)=>t.logMatchExpressions.update(await gA(A.credentialProvider,n,"logMatchExpressions.update")),disable:async(n)=>t.logMatchExpressions.disable(await gA(A.credentialProvider,n,"logMatchExpressions.disable"))},scripts:{list:async(n={})=>t.scripts.list(await gA(A.credentialProvider,n,"scripts.list")),get:async(n)=>t.scripts.get(await gA(A.credentialProvider,n,"scripts.get")),create:async(n)=>t.scripts.create(await gA(A.credentialProvider,n,"scripts.create")),update:async(n)=>t.scripts.update(await gA(A.credentialProvider,n,"scripts.update")),delete:async(n)=>t.scripts.delete(await gA(A.credentialProvider,n,"scripts.delete"))},issues:{count:async(n={})=>t.issues.count(await gA(A.credentialProvider,n,"issues.count")),create:async(n)=>t.issues.create(await gA(A.credentialProvider,n,VB.operationId)),list:async(n={})=>t.issues.list(await gA(A.credentialProvider,n,"issues.list")),search:async(n={})=>t.issues.search(await gA(A.credentialProvider,n,"issues.search")),get:async(n)=>t.issues.get(n),resolve:async(n)=>t.issues.resolve(n),ignore:async(n)=>t.issues.ignore(n),reopen:async(n)=>t.issues.reopen(n),mute:async(n)=>t.issues.mute(n),unmute:async(n)=>t.issues.unmute(n)},workItems:{create:async(n)=>t.workItems.create(n),comment:async(n)=>t.workItems.comment(n),transition:async(n)=>t.workItems.transition(n)},pullRequests:{list:async(n={})=>t.pullRequests.list(await gA(A.credentialProvider,n,"pullRequests.list"))},components:{list:async(n={})=>t.components.list(await gA(A.credentialProvider,n,"components.list")),get:async(n)=>t.components.get(n),register:async(n)=>t.components.register(await gA(A.credentialProvider,n,ZB.operationId)),deregister:async(n)=>t.components.deregister({componentId:n.componentId,...n.reason!==void 0?{reason:n.reason}:{}}),rename:async(n)=>t.components.rename(n),assignTeam:async(n)=>t.components.assignTeam(n),retirementPreview:async(n)=>t.components.retirementPreview(n),retire:async(n)=>t.components.retire(n),restorationPreview:async(n)=>t.components.restorationPreview(n),restore:async(n)=>t.components.restore(n),mergePreview:async(n)=>t.components.mergePreview(await gA(A.credentialProvider,n,"components.mergePreview")),merge:async(n)=>t.components.merge(await gA(A.credentialProvider,n,"components.merge")),relationships:{list:async(n={})=>t.components.relationships.list(await gA(A.credentialProvider,n,"components.relationships.list")),preview:async(n)=>t.components.relationships.preview(await gA(A.credentialProvider,n,"components.relationships.preview")),add:async(n)=>t.components.relationships.add(await gA(A.credentialProvider,n,"components.relationships.add")),remove:async(n)=>t.components.relationships.remove(await gA(A.credentialProvider,n,"components.relationships.remove"))},incidents:{list:async(n={})=>t.components.incidents.list(await gA(A.credentialProvider,n,"components.incidents.list"))},timeline:async(n)=>t.components.timeline(n)},billing:{getSummary:async(n={})=>t.billing.getSummary(await kA(A.credentialProvider,n)),getUsage:async(n={})=>t.billing.getUsage(await kA(A.credentialProvider,n)),listTransactions:async(n={})=>t.billing.listTransactions(await kA(A.credentialProvider,n)),previewSubscriptionCancellation:async(n={})=>t.billing.previewSubscriptionCancellation(await kA(A.credentialProvider,n)),scheduleSubscriptionCancellation:async(n={})=>t.billing.scheduleSubscriptionCancellation(await kA(A.credentialProvider,n)),resumeSubscriptionCancellation:async(n={})=>t.billing.resumeSubscriptionCancellation(await kA(A.credentialProvider,n)),getAutoTopUp:async(n={})=>t.billing.getAutoTopUp(await kA(A.credentialProvider,n)),updateAutoTopUp:async(n)=>t.billing.updateAutoTopUp(await kA(A.credentialProvider,n)),purchaseCredits:async(n)=>t.billing.purchaseCredits(await kA(A.credentialProvider,n)),listPlans:async(n={})=>t.billing.listPlans(await kA(A.credentialProvider,n)),previewPlanChange:async(n)=>t.billing.previewPlanChange(await kA(A.credentialProvider,n)),changePlan:async(n)=>t.billing.changePlan(await kA(A.credentialProvider,n)),createCheckoutSession:async(n)=>t.billing.createCheckoutSession(await kA(A.credentialProvider,n)),getCheckoutSessionStatus:async(n)=>t.billing.getCheckoutSessionStatus(await kA(A.credentialProvider,n)),createPortalSession:async(n={})=>t.billing.createPortalSession(await kA(A.credentialProvider,n)),getPaymentMethod:async(n={})=>t.billing.getPaymentMethod(await kA(A.credentialProvider,n))},tasks:{list:async(n={})=>t.tasks.list(await gA(A.credentialProvider,n,Ly.operationId))},recommendations:{list:async(n={})=>t.recommendations.list(await gA(A.credentialProvider,n,Ny.operationId))},repos:{list:async(n={})=>t.repos.list(await gA(A.credentialProvider,n,uy.operationId)),add:async(n)=>t.repos.add(await gA(A.credentialProvider,n,Uy.operationId)),remove:async(n)=>t.repos.remove(await gA(A.credentialProvider,n,Fy.operationId))},notificationDeliveryRules:{list:async(n={})=>t.notificationDeliveryRules.list(await gA(A.credentialProvider,n,"notificationDeliveryRules.list")),options:async(n={})=>t.notificationDeliveryRules.options(await gA(A.credentialProvider,n,"notificationDeliveryRules.options")),create:async(n)=>t.notificationDeliveryRules.create(await gA(A.credentialProvider,n,"notificationDeliveryRules.create")),update:async(n)=>t.notificationDeliveryRules.update(await gA(A.credentialProvider,n,"notificationDeliveryRules.update")),delete:async(n)=>t.notificationDeliveryRules.delete(await gA(A.credentialProvider,n,"notificationDeliveryRules.delete"))},notificationChannels:{getProject:async(n={})=>t.notificationChannels.getProject(await gA(A.credentialProvider,n,"notificationChannels.getProject"))}}},iO=async(A={})=>{let t=await zyA(A.fetch)(PyA(A.apiBaseUrl??JyA,"/device/code"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:A.clientId??TyA,...A.scope?{scope:A.scope}:{}})}),g=await t.json();if(!t.ok)throw PdA(g,t.status);let i=g;return{deviceCode:Ke(i.device_code,"device_code"),userCode:Ke(i.user_code,"user_code"),verificationUri:Ke(i.verification_uri,"verification_uri"),verificationUriComplete:Ke(i.verification_uri_complete,"verification_uri_complete"),expiresIn:nO(i.expires_in,"expires_in"),interval:nO(i.interval,"interval")}},QO=async(A)=>{let t=await zyA(A.fetch)(PyA(A.apiBaseUrl??JyA,"/device/token"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:SdA,device_code:A.deviceCode,client_id:A.clientId??TyA})}),g=await t.json();if(t.ok){let n=g;return{status:"authorized",accessToken:Ke(n.access_token,"access_token"),tokenType:Ke(n.token_type,"token_type"),expiresIn:nO(n.expires_in,"expires_in"),scope:typeof n.scope==="string"?n.scope:""}}let i=fyA(g);if(!i)throw Error(`Device authorization failed with status ${t.status}`);if(i.error==="authorization_pending")return{status:"pending"};if(i.error==="slow_down")return{status:"pending",interval:10};if(i.error==="access_denied")return{status:"denied",message:i.errorDescription};if(i.error==="expired_token"||i.error==="invalid_grant")return{status:"expired",message:i.errorDescription};throw Error(i.errorDescription)},ldA=(A)=>{let t=A.replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`},PyA=(A,t)=>{return`${A.replace(/\/+$/,"")}/api/auth${t}`},MdA=async(A,t)=>{return kA(A,t)},kA=async(A,t)=>{let g=t.organizationId??await A.getOrganizationId?.();return g?{...t,organizationId:g}:t},YdA=async(A,t)=>{let g=t.organizationId??await A.getOrganizationId?.();if(!g)throw new dt("BAD_REQUEST",{message:"Organization ID is required",data:{operationId:"organizations.update",missingContext:["organizationId"]},status:400});return{...t,organizationId:g}},$dA=async(A,t)=>{let g=t.projectId??await A.getProjectId?.();return g?{...t,projectId:g}:t},gA=async(A,t,g)=>{let i=t.projectId??await A.getProjectId?.();if(!i)throw new dt("BAD_REQUEST",{message:"Project ID is required",data:{operationId:g,missingContext:["projectId"]},status:400});return{...t,projectId:i}},kdA=async(A,t)=>{let g=t.projectId??await A.getProjectId?.();return g?{...t,projectId:g}:t},GdA=async(A,t)=>{let g=t.projectId??await A.getProjectId?.();return g?{...t,projectId:g}:t},JdA=async(A,t)=>{let g=t.projectId??await A.getProjectId?.();return g?{...t,projectId:g}:t},TdA=(A)=>{return{threadId:A.threadId,message:A.message,wait:A.wait??!0,timeoutSeconds:A.timeoutSeconds??20,...A.automationId!==void 0?{automationId:A.automationId}:{}}},RdA=(A)=>{if(!A||typeof A!=="object")return null;let t=A;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((g)=>typeof g==="string"):[],...typeof t.reason==="string"?{reason:t.reason}:{}}},fyA=(A)=>{if(!A||typeof A!=="object")return null;let t=A;if(typeof t.error!=="string"||typeof t.error_description!=="string")return null;return{error:t.error,errorDescription:t.error_description}},PdA=(A,t)=>{let g=fyA(A);return Error(g?.errorDescription??`Device authorization failed with status ${t}`)},zyA=(A)=>{return A??globalThis.fetch},GyA=(A,t)=>({result:t,poll:()=>A.runs.get({runId:t.runId}),waitForCompletion:async(g={})=>fdA(A,t,g)}),fdA=async(A,t,g)=>{if(t.completed)return t;let i=g.intervalMs??2000,n=Date.now(),Q=t;while(!Q.completed){if(g.timeoutMs!==void 0&&Date.now()-n>=g.timeoutMs)return Q;await zdA(i),Q=await A.runs.get({runId:Q.runId})}return Q},zdA=async(A)=>{await new Promise((t)=>globalThis.setTimeout(t,A))},Ke=(A,t)=>{if(typeof A==="string")return A;throw Error(`Expected '${t}' to be a string.`)},nO=(A,t)=>{if(typeof A==="number")return A;throw Error(`Expected '${t}' to be a number.`)};var oO=D(()=>{BB();Fv();HI();ryA();tO();tO()});var ut=(A)=>({success:!0,value:A}),wt=(A,t,g)=>({success:!1,error:A,...t!==void 0&&{statusCode:t},...g!==void 0&&{errorPayload:g}}),OdA=(A)=>{if(A===void 0)return"NETWORK_ERROR";if(A===401)return"UNAUTHORIZED";if(A===403)return"FORBIDDEN";if(A===404)return"NOT_FOUND";if(A===429)return"TOO_MANY_REQUESTS";if(A>=500)return"SERVER_ERROR";return"REQUEST_FAILED"},N=(A,t,g)=>{if(!A.success){let i=`${t}: ${A.error}`;if(g)return b(A.errorPayload??{code:OdA(A.statusCode),message:i,operationId:null});return r(i)}return A.value};var IA=D(()=>{nA()});var vdA="https://api.sazabi.com",k=async(A)=>{try{return ut(await A())}catch(t){let g=ZdA(t),i=WdA(t),n=t instanceof Error?t.message:String(t);if(g?.retryAfterSeconds!==void 0)n+=` Retry in ~${g.retryAfterSeconds}s.`;return wt(n,i,g)}},ZdA=(A)=>{if(!A||typeof A!=="object")return;let t=A;if(typeof t.code!=="string"||typeof t.message!=="string"||!t.data||typeof t.data!=="object")return;let g=t.data;if(typeof g.operationId!=="string")return;return{code:t.code,message:t.message,operationId:g.operationId,...typeof g.reason==="string"?{reason:g.reason}:{},...typeof g.retryAfterSeconds==="number"?{retryAfterSeconds:g.retryAfterSeconds}:{},...Array.isArray(g.missingContext)?{missingContext:g.missingContext.filter((i)=>typeof i==="string")}:{}}},WdA=(A)=>{if(!A||typeof A!=="object")return;let t=A;return typeof t.status==="number"?t.status:void 0},CQ=(A)=>{let t=RyA({apiBaseUrl:A.baseUrl??vdA,clientSource:"cli",sandboxActorDescriptor:A.sandboxActorDescriptor,credentialProvider:{getToken:()=>A.token,getOrganizationId:()=>A.organizationId,getProjectId:()=>A.projectId},intakeBaseUrl:A.intakeBaseUrl,tailBaseUrl:A.tailBaseUrl});return{me:()=>k(()=>t.me()),automations:{list:(g={})=>k(()=>t.automations.list(g)),get:(g)=>k(()=>t.automations.get({automationId:g})),create:(g)=>k(()=>t.automations.create(g)),update:(g)=>k(()=>t.automations.update(g)),enable:(g)=>k(()=>t.automations.enable({automationId:g})),disable:(g)=>k(()=>t.automations.disable({automationId:g})),runs:{list:(g,i={})=>k(()=>t.automations.runs.list({automationId:g,...i})),get:(g,i)=>k(()=>t.automations.runs.get({automationId:g,runId:i})),logs:(g,i)=>k(()=>t.automations.runs.logs({automationId:g,runId:i}))}},logs:{tail:(g)=>k(()=>t.logs.tail(g)),forward:(g)=>k(()=>t.logs.forward(g)),query:(g={})=>k(()=>t.logs.query(g)),schema:(g={})=>k(()=>t.logs.schema(g)),volume:(g)=>k(()=>t.logs.volume(g)),patterns:(g={})=>k(()=>t.logs.patterns(g)),nativeQuery:(g)=>k(()=>t.logs.nativeQuery(g))},organizations:{list:()=>k(()=>t.organizations.list()),get:(g)=>k(()=>t.organizations.get({organizationId:g})),create:(g)=>k(()=>t.organizations.create({name:g})),rename:(g,i)=>k(()=>t.organizations.update({organizationId:i,name:g}))},members:{list:(g={})=>k(()=>t.members.list(g)),updateRole:(g,i,n)=>k(()=>t.members.updateRole({organizationId:n,member:g,role:i})),remove:(g,i)=>k(()=>t.members.remove({organizationId:i,member:g})),invite:(g)=>k(()=>t.members.invite({organizationId:g.organizationId,email:g.email,role:g.role})),listInvitations:(g)=>k(()=>t.members.listInvitations({organizationId:g})),revokeInvitation:(g)=>k(()=>t.members.revokeInvitation({organizationId:g.organizationId,invitationId:g.invitationId}))},teams:{list:(g={})=>k(()=>t.teams.list(g)),create:(g,i,n)=>k(()=>t.teams.create({organizationId:n,name:g,...i!==void 0?{description:i}:{}})),update:(g,i,n)=>k(()=>t.teams.update({organizationId:n,teamId:g,...i.name!==void 0?{name:i.name}:{},...i.description!==void 0?{description:i.description}:{}})),delete:(g,i)=>k(()=>t.teams.delete({organizationId:i,teamId:g})),addMember:(g,i,n)=>k(()=>t.teams.addMember({organizationId:n,teamId:g,userId:i})),removeMember:(g,i,n)=>k(()=>t.teams.removeMember({organizationId:n,teamId:g,userId:i})),listMembers:(g,i)=>k(()=>t.teams.listMembers({organizationId:i,teamId:g}))},projects:{list:(g={})=>k(()=>t.projects.list(g)),get:(g)=>k(()=>t.projects.get({projectId:g})),create:(g)=>k(()=>t.projects.create(g))},threads:{list:(g={})=>k(()=>t.threads.list(g)),get:(g)=>k(()=>t.threads.get({threadId:g})),create:(g)=>k(()=>t.threads.create(g)),getStatus:(g)=>k(()=>t.threads.getStatus({threadId:g})),update:(g,i)=>k(()=>t.threads.update({threadId:g,status:i})),fork:(g,i)=>k(()=>t.threads.fork({threadId:g,messageId:i})),setVisibility:(g,i)=>k(()=>t.threads.setVisibility({threadId:g,visibility:i})),createShareLink:(g)=>k(()=>t.threads.createShareLink({threadId:g})),listShareLinks:(g)=>k(()=>t.threads.listShareLinks({threadId:g})),revokeShareLink:(g,i)=>k(()=>t.threads.revokeShareLink({threadId:g,shareId:i})),stop:(g)=>k(()=>t.threads.stop({threadId:g})),stream:(g)=>k(()=>t.threads.stream(g))},messages:{list:(g,i={})=>k(()=>t.messages.list({threadId:g,...i})),append:(g,i,n,Q,o,B)=>k(()=>t.messages.append({threadId:g,message:i,wait:n,timeoutSeconds:Q,...o!==void 0?{automationId:o}:{},...B?{ambientServiceRun:B}:{}}))},runs:{get:(g)=>k(()=>t.runs.get({runId:g})),cancel:(g)=>k(()=>t.runs.cancel({runId:g})),stream:(g)=>k(()=>t.runs.stream(g))},search:{threads:(g)=>k(()=>t.search.threads(g)),messages:(g)=>k(()=>t.search.messages(g))},publicKeys:{list:(g)=>k(()=>t.publicKeys.list(g)),get:(g,i)=>k(()=>t.publicKeys.get(i?{keyId:g,projectId:i}:{keyId:g})),ensureLogForwarding:(g)=>k(()=>t.publicKeys.ensureLogForwarding(g)),update:(g)=>k(()=>t.publicKeys.update(g)),deactivate:(g)=>k(()=>t.publicKeys.deactivate(g))},secretKeys:{list:(g)=>k(()=>t.secretKeys.list(g)),get:(g)=>k(()=>t.secretKeys.get({keyId:g})),create:(g)=>k(()=>t.secretKeys.create(g)),update:(g)=>k(()=>t.secretKeys.update(g)),delete:(g)=>k(()=>t.secretKeys.delete(g))},issues:{count:(g={})=>k(()=>t.issues.count(g)),create:(g)=>k(()=>t.issues.create(g)),list:(g={})=>k(()=>t.issues.list(g)),search:(g={})=>k(()=>t.issues.search(g)),get:(g)=>k(()=>t.issues.get({issueId:g})),resolve:(g)=>k(()=>t.issues.resolve({issueId:g})),ignore:(g)=>k(()=>t.issues.ignore({issueId:g})),reopen:(g)=>k(()=>t.issues.reopen({issueId:g})),mute:(g)=>k(()=>t.issues.mute({issueId:g})),unmute:(g)=>k(()=>t.issues.unmute({issueId:g}))},pullRequests:{list:(g={})=>k(()=>t.pullRequests.list(g))},workItems:{create:(g)=>k(()=>t.workItems.create(g)),comment:(g)=>k(()=>t.workItems.comment(g)),transition:(g)=>k(()=>t.workItems.transition(g))},components:{list:(g={})=>k(()=>t.components.list(g)),get:(g)=>k(()=>t.components.get({componentId:g})),register:(g)=>k(()=>t.components.register(g)),deregister:(g,i)=>k(()=>t.components.deregister({componentId:g,...i!==void 0?{reason:i}:{}})),rename:(g)=>k(()=>t.components.rename(g)),retirementPreview:(g)=>k(()=>t.components.retirementPreview(g)),retire:(g)=>k(()=>t.components.retire(g)),restorationPreview:(g)=>k(()=>t.components.restorationPreview(g)),restore:(g)=>k(()=>t.components.restore(g)),mergePreview:(g)=>k(()=>t.components.mergePreview(g)),merge:(g)=>k(()=>t.components.merge(g)),relationships:{list:(g={})=>k(()=>t.components.relationships.list(g)),preview:(g)=>k(()=>t.components.relationships.preview(g)),add:(g)=>k(()=>t.components.relationships.add(g)),remove:(g)=>k(()=>t.components.relationships.remove(g))},incidents:{list:(g={})=>k(()=>t.components.incidents.list(g))},timeline:(g)=>k(()=>t.components.timeline(g))},billing:{getSummary:(g={})=>k(()=>t.billing.getSummary(g)),getUsage:(g={})=>k(()=>t.billing.getUsage(g)),listTransactions:(g={})=>k(()=>t.billing.listTransactions(g)),previewSubscriptionCancellation:()=>k(()=>t.billing.previewSubscriptionCancellation()),scheduleSubscriptionCancellation:()=>k(()=>t.billing.scheduleSubscriptionCancellation()),resumeSubscriptionCancellation:()=>k(()=>t.billing.resumeSubscriptionCancellation()),getAutoTopUp:(g={})=>k(()=>t.billing.getAutoTopUp(g)),updateAutoTopUp:(g)=>k(()=>t.billing.updateAutoTopUp(g)),purchaseCredits:(g)=>k(()=>t.billing.purchaseCredits(g)),listPlans:(g={})=>k(()=>t.billing.listPlans(g)),previewPlanChange:(g)=>k(()=>t.billing.previewPlanChange(g)),changePlan:(g)=>k(()=>t.billing.changePlan(g)),createCheckoutSession:(g)=>k(()=>t.billing.createCheckoutSession(g)),getCheckoutSessionStatus:(g)=>k(()=>t.billing.getCheckoutSessionStatus(g)),createPortalSession:(g={})=>k(()=>t.billing.createPortalSession(g)),getPaymentMethod:(g={})=>k(()=>t.billing.getPaymentMethod(g))},tasks:{list:(g={})=>k(()=>t.tasks.list(g))},recommendations:{list:(g={})=>k(()=>t.recommendations.list(g))},repos:{list:(g={})=>k(()=>t.repos.list(g)),add:(g)=>k(()=>t.repos.add(g)),remove:(g)=>k(()=>t.repos.remove(g))},onboarding:{getState:(g={})=>k(()=>t.onboarding.getState(g)),skipSampleIssue:()=>k(()=>t.onboarding.skipSampleIssue()),finish:(g)=>k(()=>t.onboarding.finish(g))},notificationDeliveryRules:{list:()=>k(()=>t.notificationDeliveryRules.list()),options:()=>k(()=>t.notificationDeliveryRules.options()),create:(g)=>k(()=>t.notificationDeliveryRules.create(g)),update:(g)=>k(()=>t.notificationDeliveryRules.update(g)),delete:(g)=>k(()=>t.notificationDeliveryRules.delete({ruleId:g}))},notificationChannels:{getProject:()=>k(()=>t.notificationChannels.getProject())},logSources:{listProviders:()=>k(()=>t.logSources.listProviders()),list:(g)=>k(()=>t.logSources.list(g)),get:(g)=>k(()=>t.logSources.get({logSourceId:g})),create:(g)=>k(()=>t.logSources.create(g)),update:(g)=>k(()=>t.logSources.update(g)),delete:(g)=>k(()=>t.logSources.delete({logSourceId:g}))},logStreams:{list:(g)=>k(()=>t.logStreams.list({logSourceId:g})),get:(g)=>k(()=>t.logStreams.get({streamId:g})),create:(g)=>k(()=>t.logStreams.create(g)),update:(g)=>k(()=>t.logStreams.update(g)),delete:(g)=>k(()=>t.logStreams.delete({streamId:g})),reassign:(g)=>k(()=>t.logStreams.reassign(g))},integrations:{listProviders:()=>k(()=>t.integrations.listProviders()),listConnections:(g)=>k(()=>t.integrations.listConnections(g)),getConnection:(g)=>k(()=>t.integrations.getConnection({connectionId:g})),createConnection:(g)=>k(()=>t.integrations.createConnection(g)),beginConnect:(g)=>k(()=>t.integrations.beginConnect(g)),getConnectAttempt:(g)=>k(()=>t.integrations.getConnectAttempt({attemptId:g})),disconnectConnection:(g)=>k(()=>t.integrations.disconnectConnection({connectionId:g})),updateConnectionCredentials:(g)=>k(()=>t.integrations.updateConnectionCredentials(g))},connectedAccounts:{beginConnect:(g)=>k(()=>t.connectedAccounts.beginConnect(g)),getConnectAttempt:(g)=>k(()=>t.connectedAccounts.getConnectAttempt({attemptId:g})),list:()=>k(()=>t.connectedAccounts.list({})),disconnect:(g)=>k(()=>t.connectedAccounts.disconnect(g))},mcpConnectors:{list:(g)=>k(()=>t.mcpConnectors.list(g)),get:(g)=>k(()=>t.mcpConnectors.get(g)),details:(g)=>k(()=>t.mcpConnectors.details(g)),listProviders:()=>k(()=>t.mcpConnectors.listProviders()),beginOAuthInstall:(g)=>k(()=>t.mcpConnectors.beginOAuthInstall(g)),getOAuthInstallAttempt:(g)=>k(()=>t.mcpConnectors.getOAuthInstallAttempt(g)),disconnect:(g)=>k(()=>t.mcpConnectors.disconnect(g)),update:(g)=>k(()=>t.mcpConnectors.update(g))},sandboxPresets:{delete:(g)=>k(()=>t.sandboxPresets.delete(g)),listConnections:(g)=>k(()=>t.sandboxPresets.listConnections(g)),listTypes:()=>k(()=>t.sandboxPresets.listTypes()),test:(g)=>k(()=>t.sandboxPresets.test(g)),upsert:(g)=>k(()=>t.sandboxPresets.upsert(g))},memory:{list:(g={})=>k(()=>t.memory.list(g)),get:(g)=>k(()=>t.memory.get(g)),search:(g)=>k(()=>t.memory.search(g)),put:(g)=>k(()=>t.memory.put({kind:"note",...g})),delete:(g)=>k(()=>t.memory.delete(g))},logMatchExpressions:{list:(g={})=>k(()=>t.logMatchExpressions.list(g)),get:(g)=>k(()=>t.logMatchExpressions.get({expressionId:g})),create:(g)=>k(()=>t.logMatchExpressions.create(g)),update:(g,i={})=>k(()=>t.logMatchExpressions.update({expressionId:g,...i})),disable:(g)=>k(()=>t.logMatchExpressions.disable({expressionId:g}))},scripts:{list:(g={})=>k(()=>t.scripts.list(g)),get:(g)=>k(()=>t.scripts.get({name:g})),create:(g)=>k(()=>t.scripts.create(g)),update:(g,i={})=>k(()=>t.scripts.update({name:g,...i})),delete:(g)=>k(()=>t.scripts.delete({name:g}))}}};var Sy=D(()=>{oO();IA()});var OyA;var vyA=D(()=>{OyA={version:2,activeProfile:"default",profiles:{default:{}}}});import*as cQ from"node:fs";import*as ZyA from"node:os";import*as hO from"node:path";var bg=(A)=>{if(A===void 0||A===null)return;if(typeof A==="string")return A.length>0?A:void 0;return},VdA=(A)=>{if(typeof A!=="object"||A===null||Array.isArray(A))return;let t={};for(let[g,i]of Object.entries(A)){if(!Array.isArray(i))continue;let n=i.filter((Q)=>typeof Q==="string"&&Q.length>0);if(n.length>0)t[g]=n}return Object.keys(t).length>0?t:void 0},IO,je,XdA=()=>{if(!cQ.existsSync(IO))cQ.mkdirSync(IO,{recursive:!0,mode:448})},BO,WyA=(A)=>{BO=A},VyA=(A)=>({token:bg(A.token),activeOrganizationId:bg(A.activeOrganizationId??A.organizationId),organizationName:bg(A.organizationName),activeProjectId:bg(A.activeProjectId??A.defaultProjectId),apiBaseUrl:bg(A.apiBaseUrl),authBaseUrl:bg(A.authBaseUrl),webBaseUrl:bg(A.webBaseUrl),intakeBaseUrl:bg(A.intakeBaseUrl),tailBaseUrl:bg(A.tailBaseUrl),apiDomain:bg(A.apiDomain),webDomain:bg(A.webDomain),intakeDomain:bg(A.intakeDomain),tailDomain:bg(A.tailDomain),forwardPublicKey:bg(A.forwardPublicKey),forwardPublicKeyProjectId:bg(A.forwardPublicKeyProjectId),skippedOnboardingSteps:VdA(A.skippedOnboardingSteps)}),HdA=(A)=>({version:2,activeProfile:"default",profiles:{default:VyA(A)}}),KdA=(A)=>{let t=bg(A.activeProfile)??"default",g=typeof A.profiles==="object"&&A.profiles!==null?A.profiles:{},i={};for(let[n,Q]of Object.entries(g)){if(typeof Q!=="object"||Q===null)continue;i[n]=VyA(Q)}if(!i[t])i[t]={};return{version:2,activeProfile:t,profiles:i}},mA=()=>{try{if(!cQ.existsSync(je))return ut(OyA);let A=cQ.readFileSync(je,"utf-8"),t=JSON.parse(A),g=typeof t.version==="number"?t.version:void 0;if(g!==void 0&&g>2)return wt("Settings file requires a newer CLI version. Upgrade with 'npm install -g @sazabi/cli@latest'.");if(g===2)return ut(KdA(t));let i=HdA(t),n=at(i);if(!n.success)return n;return ut(i)}catch(A){let t=A instanceof Error?A.message:String(A);return wt(t)}},at=(A)=>{try{return XdA(),cQ.writeFileSync(je,JSON.stringify(A,null,2),{encoding:"utf-8",mode:384}),ut(void 0)}catch(t){let g=t instanceof Error?t.message:String(t);return wt(g)}},zn=(A,t)=>{if(t)return t;if(BO)return BO;let g=process.env.SAZABI_PROFILE?.trim();if(g)return g;return A.activeProfile??"default"},mt=(A,t)=>{let g=zn(A,t),i=A.profiles[g];if(i)return ut(i);if(g==="default")return ut({});return wt(`Profile '${g}' does not exist. Run 'sazabi profiles create ${g}' first.`)},oi=()=>{let A=mA();if(!A.success)return A;return mt(A.value)},xt=(A,t,g)=>{let i=zn(A,g);if(!A.profiles[i])return wt(`Profile '${i}' does not exist. Run 'sazabi profiles create ${i}' first.`);return ut({...A,profiles:{...A.profiles,[i]:{...A.profiles[i],...t}}})},XyA=(A,t)=>A?.skippedOnboardingSteps?.[t]??[],HyA=(A,t,g,i)=>{let n=mt(A,i);if(!n.success)return n;let Q={...n.value.skippedOnboardingSteps},o=Q[t]??[];if(!o.includes(g))Q[t]=[...o,g];return xt(A,{skippedOnboardingSteps:Q},i)},KyA=(A,t,g)=>{let i=mt(A,g);if(!i.success)return i;let{[t]:n,...Q}=i.value.skippedOnboardingSteps??{};return xt(A,{skippedOnboardingSteps:Object.keys(Q).length>0?Q:void 0},g)},On=(A)=>{if(!A?.forwardPublicKey&&!A?.forwardPublicKeyProjectId)return{};return{forwardPublicKey:void 0,forwardPublicKeyProjectId:void 0}};var Ng=D(()=>{vyA();IA();IO=hO.join(ZyA.homedir(),".sazabi"),je=hO.join(IO,"settings.json")});var fi=(A)=>{let{cliFlag:t,globalUrl:g,globalDomain:i,buildUrlFromDomain:n,defaultUrl:Q}=A;if(t)return t;let o=process.env.SAZABI_API_URL?.trim();if(o)return o;if(g)return g;if(i)return n(i);return Q},P=(A)=>{let{tokenFlag:t,organizationIdFlag:g,projectIdFlag:i,jsonMode:n}=A,Q=t?.trim(),o=process.env.SAZABI_TOKEN?.trim(),B=process.env.SAZABI_ORGANIZATION_ID?.trim(),h=process.env.SAZABI_PROJECT_ID?.trim(),e=N(oi(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",n),C=e.token?.trim(),c=(Q&&Q.length>0?Q:void 0)||(o&&o.length>0?o:void 0)||C,E=Q&&Q.length>0?"flag":o&&o.length>0?"environment":"settings";if(!c||c.length===0){if(n)return b("Not authenticated. Set SAZABI_TOKEN, pass --token, run 'sazabi auth login', or run 'sazabi auth save <token>'.");return r("Not authenticated. Set SAZABI_TOKEN, pass --token, run 'sazabi auth login', or run 'sazabi auth save <token>'.")}let y,w;if(g)y=g,w="flag";else if(B&&B.length>0)y=B,w="environment";else if(e.activeOrganizationId)y=e.activeOrganizationId,w="settings";let a,u;if(i)a=i,u="flag";else if(h&&h.length>0)a=h,u="environment";else if(e.activeProjectId)a=e.activeProjectId,u="settings";return{token:c,type:"token",projectId:a,organizationId:y,tokenSource:E,organizationSource:w,projectSource:u}},ly=(A)=>{let t=N(oi(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",A?.jsonMode);return fi({cliFlag:A?.apiBaseUrlFlag,globalUrl:t.apiBaseUrl,globalDomain:t.apiDomain,buildUrlFromDomain:(g)=>`https://api.${g}`,defaultUrl:"https://api.sazabi.com"})},z=(A)=>{let t=ly({apiBaseUrlFlag:A.apiBaseUrlFlag,jsonMode:A.jsonMode});return CQ({token:A.token,baseUrl:t,organizationId:A.organizationId,projectId:A.projectId,sandboxActorDescriptor:process.env.SAZABI_SANDBOX_ACTOR})},jyA,eO,bN=async(A)=>{let t=N(oi(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",A.jsonMode),g=fi({cliFlag:A.apiBaseUrlFlag,globalUrl:t.apiBaseUrl,globalDomain:t.apiDomain,buildUrlFromDomain:(h)=>`https://api.${h}`,defaultUrl:"https://api.sazabi.com"}),i=`${A.token}@${g}@${A.projectId??""}`,n=jyA.get(i);if(n)return n;let Q=eO.get(i);if(Q)return Q;if(!A.projectId){if(A.jsonMode)return b("Project ID is required. Run 'sazabi projects use <project-id>' or set SAZABI_PROJECT_ID.");return r("Project ID is required. Run 'sazabi projects use <project-id>' or set SAZABI_PROJECT_ID.")}let o=A.projectId,B=(async()=>{let e=await CQ({token:A.token,baseUrl:g,projectId:o}).projects.get(o),c=N(e,"Couldn't fetch project info (run 'sazabi projects list' to verify the project ID)",A.jsonMode).project;return jyA.set(i,c),c})();eO.set(i,B);try{return await B}finally{eO.delete(i)}},rN=(A)=>{let t=A.trim().toLowerCase(),g=/^[a-z][a-z0-9+.-]*:\/\//.test(t)?t:`https://${t}`,i=t;try{i=new URL(g).hostname.toLowerCase()}catch{i=t.replace(/^[a-z][a-z0-9+.-]*:\/\//,"").replace(/[/?#].*$/,"").replace(/:\d+$/,"")}return`https://app.${i.replace(/^(?:app\.)+/,"")}`},jdA=(A)=>{try{let t=new URL(A),g=t.hostname.toLowerCase();if(!g.startsWith("api."))return null;return`${t.protocol}//app.${g.slice(4)}`}catch{return null}},zi=(A)=>{let t=(i)=>i.replace(/\/+$/,"");if(A)return t(A);let g=N(oi(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)");if(g.webBaseUrl)return t(g.webBaseUrl);if(g.webDomain)return rN(g.webDomain);if(g.apiDomain)return rN(g.apiDomain);if(g.apiBaseUrl){let i=jdA(g.apiBaseUrl);if(i)return i}return"https://app.sazabi.com"},dg=(A,t)=>{if(A&&A.length>0)return A;let g="No project selected. Pass --project-id, set SAZABI_PROJECT_ID, or run 'sazabi projects use <project-id>'.";if(t)return b(g);return r(g)},uo=(A,t)=>{return`${zi(t)}/projects/${A}`},Ot=(A,t,g,i)=>{let n=`${zi(g)}/projects/${A}/threads/${t}`;return i?`${n}?messageId=${encodeURIComponent(i)}`:n},_yA=(A,t,g,i)=>{return Ot(A,t,g,i)},myA=(A,t,g)=>{return`${uo(A,g)}/issues/${t}`},xyA=(A,t,g)=>{return`${uo(A,g)}/automations/${t}`},qyA=(A,t)=>{return`${uo(A,t)}/status`},dyA=(A,t,g)=>{return`${uo(A,g)}/settings/log-source-providers/${t}`},pyA=(A,t,g)=>{return`${uo(A,g)}/settings/mcp-connectors/${t}`},NN=(A,t,g)=>{return`${uo(A,g)}/settings/sandbox/catalog/${t}`},syA=(A,t)=>{return`https://otlp.${t}.intake.${A}`};var aA=D(()=>{nA();Sy();IA();Ng();jyA=new Map,eO=new Map});var dN,ebA=(A)=>{dN.set(A.name,A)},pN=(A)=>{return dN.get(A)},dy=()=>{return Array.from(dN.values())},CbA=(A)=>{return dN.has(A)};var F1=D(()=>{dN=new Map});async function Y1(A){let t=await A.publicKeys.list({limit:20});if(!t.success)return[];return t.value.publicKeys.map((g)=>({value:g.id,description:g.name}))}async function $1(A){let t=await A.secretKeys.list({limit:20});if(!t.success)return[];return t.value.secretKeys.map((g)=>({value:g.id,description:g.name}))}async function sy(A){let t=await A.logSources.list();if(!t.success)return[];return t.value.logSources.map((g)=>({value:g.id,description:g.name??g.provider}))}async function EbA(A){let t=await A.members.list();if(!t.success)return[];return t.value.members.map((g)=>({value:g.userId,description:g.name??g.email}))}var _ot=3000,mot,ybA=async(A,t,g)=>{try{let i=mot[A]?.[t];if(!i)return[];let n=oi();if(!n.success)return[];let Q=n.value,o=process.env.SAZABI_TOKEN?.trim()||Q.token?.trim();if(!o)return[];let B=fi({globalUrl:Q.apiBaseUrl,globalDomain:Q.apiDomain,buildUrlFromDomain:(C)=>`https://api.${C}`,defaultUrl:"https://api.sazabi.com"}),h=CQ({token:o,baseUrl:B,organizationId:Q.activeOrganizationId,projectId:Q.activeProjectId});return(await Promise.race([i(h),new Promise((C)=>setTimeout(()=>C([]),_ot))])).filter((C)=>C.value.startsWith(g))}catch{return[]}};var DbA=D(()=>{Sy();aA();Ng();mot={threads:{get:async(A)=>{let t=await A.threads.list({limit:20});if(!t.success)return[];return t.value.threads.map((g)=>({value:g.id,description:g.title??void 0}))}},projects:{use:async(A)=>{let t=await A.projects.list();if(!t.success)return[];return t.value.projects.map((g)=>({value:g.id,description:g.name}))}},organizations:{use:async(A)=>{let t=await A.organizations.list();if(!t.success)return[];return t.value.organizations.map((g)=>({value:g.id,description:g.name}))},rename:async(A)=>{let t=await A.organizations.list();if(!t.success)return[];return t.value.organizations.map((g)=>({value:g.id,description:g.name}))}},"public-keys":{get:Y1,update:Y1,deactivate:Y1},"secret-keys":{get:$1,update:$1,delete:$1},"log-sources":{get:sy,enable:sy,disable:sy,delete:sy,remove:sy},members:{"update-role":EbA,remove:EbA}}});var abA={};Bi(abA,{parseCompletionContext:()=>dot,getCompletions:()=>pot});var xot,qot,dot=(A)=>{let t=A.length>0?A:[""],g=t.length-1,i=t[g]??"";return{words:t,currentIndex:g,partial:i}},pot=async(A)=>{let{words:t,currentIndex:g,partial:i}=A,n=t[g-1];if(n==="--profile")return gIt(i);let Q=tIt(t),o=Math.max(0,Q.length-(t.length-g));if(o===0)return sot(i);let B=Q[0]??"",h=pN(B);if(!h)return[];if(o===1&&h.subcommands){if(i.startsWith("-"))return wbA(h.options,Q);return AIt(h,i)}let e=h.subcommands?Q[1]:void 0,c=(e?h.subcommands?.[e]:void 0)?.options??h.options;if(i.startsWith("-"))return wbA(c,Q);if(n?.startsWith("--")){let E=n.slice(2);if(c?.[E]?.type==="string"){let w=`${B}:${e??""}`,a=qot[w]?.[E]??xot[E];if(a)return a.filter((u)=>u.startsWith(i)).map((u)=>({value:u}));return[]}}return ybA(B,e??"",i)},sot=(A)=>{let g=dy().filter((n)=>n.name.startsWith(A)).map((n)=>({value:n.name,description:n.description})),i=[{value:"--help",description:"Show help"},{value:"--version",description:"Show version"},{value:"--profile",description:"Use a named profile"}];for(let n of i)if(n.value.startsWith(A))g.push(n);return g},AIt=(A,t)=>{if(!A.subcommands)return[];return Object.values(A.subcommands).filter((g)=>g.name.startsWith(t)).map((g)=>({value:g.name,description:g.description}))},wbA=(A,t)=>{let g=t[t.length-1]??"",i=new Set(t.filter((Q)=>Q.startsWith("--")).map((Q)=>Q.replace(/=.*/,""))),n=[];if(!i.has("--help")&&"--help".startsWith(g))n.push({value:"--help",description:"Show help"});if(!i.has("--profile")&&"--profile".startsWith(g))n.push({value:"--profile",description:"Use a named profile"});if(!A)return n;for(let[Q,o]of Object.entries(A)){let B=`--${Q}`;if(i.has(B))continue;if(!B.startsWith(g))continue;n.push({value:B,description:o.description})}return n},tIt=(A)=>{let t=[];for(let g=0;g<A.length;g++){let i=A[g];if(i==="--profile"&&g+1<A.length)g++;else if(i.startsWith("--profile="));else t.push(i)}return t},gIt=(A)=>{try{let t=mA();if(!t.success)return[];return Object.keys(t.value.profiles).filter((g)=>g.startsWith(A)).map((g)=>({value:g,description:g===t.value.activeProfile?"active":void 0}))}catch{return[]}};var rbA=D(()=>{F1();Ng();DbA();xot={status:["regular","archived"],format:["json","text"]},qot={"members:update-role":{role:["admin","member"]},"messages:search":{role:["user","assistant"]},"messages:list":{role:["user","assistant"]}}});nA();nA();nA();import{parseArgs as X1}from"node:util";var S=(A,t,g={})=>{let i=Object.hasOwn(t,"json")&&A.includes("--json"),n=(C,c)=>{if(i)b({code:C,message:c,operationId:null});throw r(c),Error("Unreachable")},Q=(()=>{try{return X1({args:A,options:t,allowPositionals:Boolean(g.allowPositionals),strict:!1,tokens:!0})}catch(C){let c=new Set(Object.keys(t)),E=new Set(Object.values(t).map((w)=>w.short).filter((w)=>Boolean(w)));try{let w=X1({args:A,options:t,allowPositionals:!0,strict:!1,tokens:!0}),a=[...new Set((w.tokens??[]).flatMap((u)=>u.kind==="option"?[u]:[]).filter((u)=>!c.has(u.name)&&!(u.name.length===1&&E.has(u.name))).map((u)=>u.name.length>1?`--${u.name}`:`-${u.name}`))];if(a.length>0)return n("UNEXPECTED_ARGUMENT",`Unknown option${a.length>1?"s":""}: ${a.join(", ")}. Run the command with -h for usage.`)}catch{}let y=C instanceof Error?C.message:"Invalid arguments.";return n("INVALID_ARGUMENT",`${y.endsWith(".")?y:`${y}.`} Run the command with -h for usage.`)}})(),o=Object.hasOwn(t,"json")&&Q.values.json===!0,B=new Set(Object.keys(t)),h=new Set(Object.entries(t).map(([,C])=>C.short).filter((C)=>Boolean(C))),e=[];if(Array.isArray(Q.tokens))for(let C of Q.tokens){if(C.kind!=="option")continue;let c=C.name,E=c.length>1;if(!(B.has(c)||!E&&h.has(c))){let w=E?`--${c}`:`-${c}`;if(!e.includes(w))e.push(w)}}for(let C of Object.keys(Q.values))if(!B.has(C)){let c=C.length>1?`--${C}`:`-${C}`;if(!e.includes(c))e.push(c)}if(e.length>0){let C=`Unknown option${e.length>1?"s":""}: ${e.join(", ")}. Run the command with -h for usage.`;if(o)b({code:"UNEXPECTED_ARGUMENT",message:C,operationId:null});r(C)}for(let[C,c]of Object.entries(t))if(c.type==="string"&&Q.values[C]===!0){let E=C.length===1?`-${C}`:`--${C}`,y=`Option ${E} requires a value. Use '${E} <value>'.`;n("INVALID_ARGUMENT",y)}for(let[C,c]of Object.entries(t)){let E=Q.values[C];if(c.type==="string"&&typeof E==="string"){if(E.length===0){let w=C.length===1?`-${C}`:`--${C}`;n("INVALID_ARGUMENT",`Option ${w} requires a non-empty value.`)}if(E.startsWith("--")||E.length===2&&E[0]==="-"&&/[a-zA-Z]/.test(E.charAt(1))){let a=`Option ${C.length===1?`-${C}`:`--${C}`} received "${E}" as its value. Did you forget to provide a value?`;n("INVALID_ARGUMENT",a)}}}if(!g.allowPositionals&&Q.positionals.length>0)n("UNEXPECTED_ARGUMENT",`Unexpected argument${Q.positionals.length>1?"s":""}: ${Q.positionals.join(", ")}. Run the command with -h for usage.`);return{values:Q.values,positionals:Q.positionals}};var oD=(A,t)=>{if(A?.json?.type!=="boolean")throw Error(`${t} must include a boolean --json option (enforced by CommandBuilder)`)};class H1{name;description;handler;subcommands;options;examples;positionalArgs;allowNoJson=!1;constructor(A,t,g){this.name=A,this.description=t,this.handler=g}withOptions(A){return this.options=A,this}withSubcommands(A){return this.subcommands=A,this}withExamples(A){return this.examples=A,this}withPositionalArgs(A){return this.positionalArgs=A,this}build(){if(!this.handler&&!this.subcommands)throw Error(`Subcommand "${this.name}" must have either a handler or subcommands`);if(!this.allowNoJson&&this.handler)oD(this.options,`Subcommand "${this.name}"`);if(!this.allowNoJson&&this.subcommands){for(let[A,t]of Object.entries(this.subcommands))if(!t.subcommands)oD(t.options,`Subcommand "${this.name} ${A}"`)}return{name:this.name,description:this.description,handler:this.handler,subcommands:this.subcommands,options:this.options,examples:this.examples,positionalArgs:this.positionalArgs}}allowWithoutJson(){return this.allowNoJson=!0,this}}class K1{name;description;handler;subcommands;options;examples;positionalArgs;allowNoJson=!1;constructor(A,t){this.name=A,this.description=t}withHandler(A){return this.handler=A,this}withSubcommands(A){return this.subcommands=A,this}withOptions(A){return this.options=A,this}withExamples(A){return this.examples=A,this}withPositionalArgs(A){return this.positionalArgs=A,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)oD(this.options,`Command "${this.name}"`);if(this.subcommands)for(let[A,t]of Object.entries(this.subcommands)){if(t.subcommands)continue;oD(t.options,`Subcommand "${this.name} ${A}"`)}}return{name:this.name,description:this.description,handler:this.handler,subcommands:this.subcommands,options:this.options,examples:this.examples,positionalArgs:this.positionalArgs}}allowWithoutJson(){return this.allowNoJson=!0,this}}var QA=(A,t)=>{return new K1(A,t)},U=(A,t,g)=>{return new H1(A,t,g)};nA();var Cg=(A,t,g,i,n)=>{let Q=Number.parseInt(A,10);if(Number.isNaN(Q)||Q<t||Q>g){let o=`${i} must be between ${t} and ${g}.`;if(n)return b(o);return r(o)}return Q},An=(A,t,g,i)=>{if(!t.includes(A)){let n=t.map((o)=>`"${o}"`).join(" or "),Q=`${g} must be ${n}.`;if(i)return b(Q);return r(Q)}return A};nA();aA();IA();var cO=(A)=>{let t=[];for(let g of A){let i=0;for(let n of g.content){if(n.type!=="artifact")continue;t.push({id:`${g.id}:${i}`,messageId:g.id,name:n.name,toolCallId:n.toolCallId??null,createdAt:g.createdAt,data:n.data}),i+=1}}return t},tDA=(A)=>{let t=A.lastIndexOf(":");if(t<=0||t===A.length-1)return null;let g=A.slice(0,t),i=A.slice(t+1);if(!/^\d+$/.test(i))return null;return{messageId:g,index:Number.parseInt(i,10)}},gDA=(A,t)=>{return cO(A).find((g)=>g.id===t)},CO=(A)=>typeof A==="object"&&A!==null&&!Array.isArray(A),ADA=(A)=>{let t=A===null||A===void 0?"":typeof A==="object"?JSON.stringify(A):String(A);if(/[",\n\r]/.test(t))return`"${t.replace(/"/g,'""')}"`;return t},_dA=(A)=>{if(Array.isArray(A)&&A.every(CO))return A;if(CO(A))for(let t of["rows","data","items","points"]){let g=A[t];if(Array.isArray(g)&&g.every(CO))return g}return null},nDA=(A)=>{let t=_dA(A);if(!t||t.length===0)return null;let g=[];for(let n of t)for(let Q of Object.keys(n))if(!g.includes(Q))g.push(Q);if(g.length===0)return null;let i=[g.map(ADA).join(",")];for(let n of t)i.push(g.map((Q)=>ADA(n[Q])).join(","));return i.join(`
|
|
8709
|
+
`),...g?{id:g}:{}}),n()};return{line:(o)=>{if(o===""){Q();return}if(o.startsWith(":"))return;let B=o.indexOf(":"),h=B===-1?o:o.slice(0,B),e=B===-1?"":o.slice(B+1),C=e.startsWith(" ")?e.slice(1):e;if(h==="event"){t=C||"message";return}if(h==="data"){i.push(C);return}if(h==="id"&&!C.includes("\x00"))g=C},flush:Q}},udA=(A)=>{try{let t=byA.safeParse(JSON.parse(A));if(!t.success)return[];return t.data.data}catch{return[]}},uyA=(A)=>{return A instanceof Error?A:Error(String(A))},UyA=(A)=>{return A instanceof Error&&A.name==="AbortError"},UdA=(A)=>{return A.message.startsWith("Authentication failed")||A.message.startsWith("Forbidden (")||A.message.startsWith("Wrong region (")||A.message.startsWith("Client error (")},FdA=async(A,t,g,i={},n=3,Q=1e4)=>{let o;for(let B=0;B<=n;B+=1){let h=new AbortController,e=globalThis.setTimeout(()=>h.abort(),Q);try{let C=await A(t,{method:"POST",headers:{"content-type":"application/json",...i},body:JSON.stringify(g),signal:h.signal});if(C.ok)return;let c=await C.text();if(C.status===401||C.status===403)throw Error("Authentication failed. Check your public key.");if(C.status>=400&&C.status<500&&C.status!==429)throw Error(`Client error (${C.status}): ${c}`);o=Error(C.status===429?`Rate limited (429): ${c}`:`Server error (${C.status}): ${c}`)}catch(C){let c=C instanceof Error?C.message:String(C);if(c.startsWith("Authentication failed")||c.startsWith("Client error ("))throw C instanceof Error?C:Error(c);o=C instanceof Error&&C.name==="AbortError"?Error("Request timed out"):C instanceof Error?C:Error(String(C))}finally{globalThis.clearTimeout(e)}if(B<n)await $yA(FyA*2**B)}throw Error(`Failed after ${n+1} attempts: ${o?.message??"Unknown error"}`)},LdA=(A)=>{return A.resourceLogs?.reduce((t,g)=>t+(g.scopeLogs?.reduce((i,n)=>i+(n.logRecords?.length??0),0)??0),0)??0},$yA=async(A,t)=>{if(t?.aborted)return;await new Promise((g)=>{let i=globalThis.setTimeout(g,A);t?.addEventListener("abort",()=>{globalThis.clearTimeout(i),g()},{once:!0})})},kyA=(A,t,g)=>{return new dt("BAD_REQUEST",{message:t,data:{operationId:A,missingContext:g}})};var tO=D(()=>{BB();NyA();TA();sqA=I.object({projectId:I.string().uuid().optional().describe("Project to tail logs for. Auto-filled from CLI and SDK context when omitted."),filters:pz.optional().describe("Optional filters applied by the tail SSE service.")}),AdA=I.object({publicKey:I.string().min(1).describe("Public key for intake auth. Create or list one via the public key endpoints."),logs:I.custom((A)=>typeof A==="object"&&A!==null).describe("OTLP logs export request payload to send to the intake service.")}),tdA=I.object({forwardedCount:I.number().int().nonnegative().describe("Number of log records accepted by the intake request."),failedCount:I.number().int().nonnegative().describe("Number of log records rejected by the intake request.")}),ndA=new Set(["15006","3010"])});var gO="https://api.sazabi.com",JyA="https://api.platform.sazabi.com",TyA="sazabi-cli",SdA="urn:ietf:params:oauth:grant-type:device_code",RyA=(A)=>{let t=$u(new Vu(dz,{url:ldA(A.apiBaseUrl??gO),headers:async()=>{let n=new Headers({authorization:`Bearer ${await A.credentialProvider.getToken()}`});if(A.clientSource)n.set("x-sazabi-client-source",A.clientSource);if(A.sandboxActorDescriptor)n.set("x-sazabi-sandbox-actor",A.sandboxActorDescriptor);return n},fetch:A.fetch,customErrorResponseBodyDecoder:(n,Q)=>{let o=RdA(n);if(!o)return null;return new dt(o.code,{message:o.message,status:Q.status,data:{operationId:o.operationId,missingContext:o.missingContext,...o.reason!==void 0?{reason:o.reason}:{},...o.retryAfterSeconds!==void 0?{retryAfterSeconds:o.retryAfterSeconds}:{}}})}})),g=lyA({raw:t,credentialProvider:A.credentialProvider,fetch:A.fetch,apiBaseUrl:A.apiBaseUrl??gO,intakeBaseUrl:A.intakeBaseUrl,tailBaseUrl:A.tailBaseUrl}),i=ayA({credentialProvider:A.credentialProvider,fetch:A.fetch,apiBaseUrl:A.apiBaseUrl??gO,clientSource:A.clientSource});return{raw:t,me:async()=>t.me({}),automations:{list:async(n={})=>t.automations.list(await gA(A.credentialProvider,n,"automations.list")),get:async(n)=>t.automations.get(await gA(A.credentialProvider,n,"automations.get")),create:async(n)=>t.automations.create(await gA(A.credentialProvider,n,"automations.create")),update:async(n)=>t.automations.update(await gA(A.credentialProvider,n,"automations.update")),enable:async(n)=>t.automations.enable(await gA(A.credentialProvider,n,"automations.enable")),disable:async(n)=>t.automations.disable(await gA(A.credentialProvider,n,"automations.disable")),runs:{list:async(n)=>t.automations.runs.list(await gA(A.credentialProvider,n,"automations.runs.list")),get:async(n)=>t.automations.runs.get(await gA(A.credentialProvider,n,"automations.runs.get")),logs:async(n)=>t.automations.runs.logs(await gA(A.credentialProvider,n,"automations.runs.logs"))}},logs:{...g,query:async(n={})=>t.logs.query(await gA(A.credentialProvider,n,dB.operationId)),schema:async(n={})=>t.logs.schema(await gA(A.credentialProvider,n,pB.operationId)),volume:async(n)=>t.logs.volume(await gA(A.credentialProvider,n,sB.operationId)),patterns:async(n={})=>t.logs.patterns(await gA(A.credentialProvider,n,Ah.operationId)),nativeQuery:async(n)=>t.logs.nativeQuery(await gA(A.credentialProvider,n,th.operationId))},onboarding:{getState:async(n={})=>t.onboarding.getState(await $dA(A.credentialProvider,n)),skipSampleIssue:async(n)=>t.onboarding.skipSampleIssue(n??{}),finish:async(n)=>t.onboarding.finish(n)},organizations:{list:async()=>t.organizations.list({}),get:async(n)=>t.organizations.get(n),create:async(n)=>t.organizations.create(n),update:async(n)=>t.organizations.update(await YdA(A.credentialProvider,n))},members:{list:async(n={})=>t.members.list(await kA(A.credentialProvider,n)),updateRole:async(n)=>t.members.updateRole(await kA(A.credentialProvider,n)),remove:async(n)=>{let Q=await kA(A.credentialProvider,n);return t.members.remove({params:{member:Q.member},query:{organizationId:Q.organizationId}})},invite:async(n)=>t.members.invite(await kA(A.credentialProvider,n)),listInvitations:async(n={})=>t.members.listInvitations(await kA(A.credentialProvider,n)),revokeInvitation:async(n)=>{let Q=await kA(A.credentialProvider,n);return t.members.revokeInvitation({params:{invitationId:Q.invitationId},query:{organizationId:Q.organizationId}})}},teams:{list:async(n={})=>t.teams.list(await kA(A.credentialProvider,n)),create:async(n)=>t.teams.create(await kA(A.credentialProvider,n)),update:async(n)=>t.teams.update(await kA(A.credentialProvider,n)),delete:async(n)=>{let Q=await kA(A.credentialProvider,n);return t.teams.delete({params:{teamId:Q.teamId},query:{organizationId:Q.organizationId}})},addMember:async(n)=>t.teams.addMember(await kA(A.credentialProvider,n)),removeMember:async(n)=>{let Q=await kA(A.credentialProvider,n);return t.teams.removeMember({params:{teamId:Q.teamId,userId:Q.userId},query:{organizationId:Q.organizationId}})},listMembers:async(n)=>t.teams.listMembers(await kA(A.credentialProvider,n))},publicKeys:{list:async(n={})=>t.publicKeys.list(await gA(A.credentialProvider,n,XB.operationId)),get:async(n)=>t.publicKeys.get(await gA(A.credentialProvider,n,HB.operationId)),ensureLogForwarding:async(n={})=>t.publicKeys.ensureLogForwarding(await gA(A.credentialProvider,n,KB.operationId)),update:async(n)=>t.publicKeys.update(await gA(A.credentialProvider,n,jB.operationId)),deactivate:async(n)=>{let Q=await gA(A.credentialProvider,n,_B.operationId);return t.publicKeys.deactivate({params:{keyId:Q.keyId},query:{projectId:Q.projectId}})}},secretKeys:{list:async(n={})=>t.secretKeys.list(n),get:async(n)=>t.secretKeys.get(n),create:async(n)=>t.secretKeys.create(n),update:async(n)=>t.secretKeys.update(n),delete:async(n)=>{await t.secretKeys.delete({params:{keyId:n.keyId}})}},search:{threads:async(n)=>t.search.threads(await gA(A.credentialProvider,n,Xe.operationId)),messages:async(n)=>t.search.messages(await gA(A.credentialProvider,n,He.operationId))},projects:{list:async(n={})=>t.projects.list(await MdA(A.credentialProvider,n)),get:async(n)=>t.projects.get(n),create:async(n)=>t.projects.create(await kA(A.credentialProvider,n))},messages:{list:async(n)=>t.messages.list(n),append:async(n)=>GyA(t,await t.messages.append(TdA(n)))},threads:{list:async(n={})=>t.threads.list(await kdA(A.credentialProvider,n)),get:async(n)=>t.threads.get(n),getStatus:async(n)=>t.threads.getStatus(n),stop:async(n)=>t.threads.stop(n),create:async(n)=>GyA(t,await t.threads.create(await JdA(A.credentialProvider,n))),update:async(n)=>t.threads.update(n),fork:async(n)=>t.threads.fork(n),setVisibility:async(n)=>t.threads.setVisibility(n),createShareLink:async(n)=>t.threads.createShareLink(n),listShareLinks:async(n)=>t.threads.listShareLinks(n),revokeShareLink:async(n)=>t.threads.revokeShareLink(n),stream:async(n)=>i.streamThread(n)},runs:{list:async(n={})=>t.runs.list(await GdA(A.credentialProvider,n)),listForThread:async(n)=>t.runs.listForThread(n),get:async(n)=>t.runs.get(n),cancel:async(n)=>t.runs.cancel(n),stream:async(n)=>i.streamRun(n)},logSources:{listProviders:async()=>t.logSources.listProviders({}),list:async(n={})=>t.logSources.list(await gA(A.credentialProvider,n,xB.operationId)),get:async(n)=>t.logSources.get(n),create:async(n)=>t.logSources.create(await gA(A.credentialProvider,n,qB.operationId)),update:async(n)=>t.logSources.update(n),delete:async(n)=>t.logSources.delete(n)},logStreams:{list:async(n)=>t.logStreams.list(n),get:async(n)=>t.logStreams.get(n),create:async(n)=>t.logStreams.create(n),update:async(n)=>t.logStreams.update(n),delete:async(n)=>t.logStreams.delete(n),reassign:async(n)=>t.logStreams.reassign(n)},connectedAccounts:{beginConnect:async(n)=>t.connectedAccounts.beginConnect(await kA(A.credentialProvider,n)),getConnectAttempt:async(n)=>t.connectedAccounts.getConnectAttempt(await kA(A.credentialProvider,n)),list:async(n={})=>t.connectedAccounts.list(await kA(A.credentialProvider,n)),disconnect:async(n)=>t.connectedAccounts.disconnect(await kA(A.credentialProvider,n))},integrations:{listProviders:async(n={})=>t.integrations.listProviders(await kA(A.credentialProvider,n)),listConnections:async(n={})=>t.integrations.listConnections(await kA(A.credentialProvider,n)),getConnection:async(n)=>t.integrations.getConnection(await kA(A.credentialProvider,n)),createConnection:async(n)=>t.integrations.createConnection(await kA(A.credentialProvider,n)),beginConnect:async(n)=>t.integrations.beginConnect(await kA(A.credentialProvider,n)),getConnectAttempt:async(n)=>t.integrations.getConnectAttempt(await kA(A.credentialProvider,n)),disconnectConnection:async(n)=>t.integrations.disconnectConnection(await kA(A.credentialProvider,n)),updateConnectionCredentials:async(n)=>t.integrations.updateConnectionCredentials(await kA(A.credentialProvider,n))},mcpConnectors:{list:async(n={})=>t.mcpConnectors.list(await gA(A.credentialProvider,n,Ne.operationId)),get:async(n)=>t.mcpConnectors.get(await gA(A.credentialProvider,n,ue.operationId)),details:async(n)=>t.mcpConnectors.details(await gA(A.credentialProvider,n,Ue.operationId)),listProviders:async()=>t.mcpConnectors.listProviders({}),search:async(n={})=>t.mcpConnectors.search(await gA(A.credentialProvider,n,Fe.operationId)),describe:async(n)=>t.mcpConnectors.describe(await gA(A.credentialProvider,n,Le.operationId)),call:async(n)=>t.mcpConnectors.call(await gA(A.credentialProvider,n,Se.operationId)),create:async(n)=>t.mcpConnectors.create(await gA(A.credentialProvider,n,le.operationId)),update:async(n)=>t.mcpConnectors.update(await gA(A.credentialProvider,n,Me.operationId)),disconnect:async(n)=>{await t.mcpConnectors.disconnect(await gA(A.credentialProvider,n,Ye.operationId))},setReadOnly:async(n)=>t.mcpConnectors.setReadOnly(await gA(A.credentialProvider,n,$e.operationId)),beginOAuthInstall:async(n)=>t.mcpConnectors.beginOAuthInstall(await gA(A.credentialProvider,n,ke.operationId)),getOAuthInstallAttempt:async(n)=>t.mcpConnectors.getOAuthInstallAttempt(await gA(A.credentialProvider,n,Ge.operationId))},sandboxPresets:{delete:async(n)=>t.sandboxPresets.deletePreset(await gA(A.credentialProvider,n,We.operationId)),listConnections:async(n={})=>t.sandboxPresets.listConnections(await gA(A.credentialProvider,n,ve.operationId)),listTypes:async()=>t.sandboxPresets.listTypes({}),test:async(n)=>t.sandboxPresets.testPreset(await gA(A.credentialProvider,n,Ve.operationId)),upsert:async(n)=>t.sandboxPresets.upsertPreset(await gA(A.credentialProvider,n,Ze.operationId))},memory:{list:async(n={})=>t.memory.list(await gA(A.credentialProvider,n,Re.operationId)),get:async(n)=>t.memory.get(await gA(A.credentialProvider,n,Te.operationId)),put:async(n)=>t.memory.put(await gA(A.credentialProvider,n,Je.operationId)),search:async(n)=>t.memory.search(await gA(A.credentialProvider,n,Pe.operationId)),delete:async(n)=>t.memory.delete(await gA(A.credentialProvider,n,fe.operationId))},logMatchExpressions:{list:async(n={})=>t.logMatchExpressions.list(await gA(A.credentialProvider,n,"logMatchExpressions.list")),get:async(n)=>t.logMatchExpressions.get(await gA(A.credentialProvider,n,"logMatchExpressions.get")),create:async(n)=>t.logMatchExpressions.create(await gA(A.credentialProvider,n,"logMatchExpressions.create")),update:async(n)=>t.logMatchExpressions.update(await gA(A.credentialProvider,n,"logMatchExpressions.update")),disable:async(n)=>t.logMatchExpressions.disable(await gA(A.credentialProvider,n,"logMatchExpressions.disable"))},scripts:{list:async(n={})=>t.scripts.list(await gA(A.credentialProvider,n,"scripts.list")),get:async(n)=>t.scripts.get(await gA(A.credentialProvider,n,"scripts.get")),create:async(n)=>t.scripts.create(await gA(A.credentialProvider,n,"scripts.create")),update:async(n)=>t.scripts.update(await gA(A.credentialProvider,n,"scripts.update")),delete:async(n)=>t.scripts.delete(await gA(A.credentialProvider,n,"scripts.delete"))},issues:{count:async(n={})=>t.issues.count(await gA(A.credentialProvider,n,"issues.count")),create:async(n)=>t.issues.create(await gA(A.credentialProvider,n,VB.operationId)),list:async(n={})=>t.issues.list(await gA(A.credentialProvider,n,"issues.list")),search:async(n={})=>t.issues.search(await gA(A.credentialProvider,n,"issues.search")),get:async(n)=>t.issues.get(n),resolve:async(n)=>t.issues.resolve(n),ignore:async(n)=>t.issues.ignore(n),reopen:async(n)=>t.issues.reopen(n),mute:async(n)=>t.issues.mute(n),unmute:async(n)=>t.issues.unmute(n)},workItems:{create:async(n)=>t.workItems.create(n),comment:async(n)=>t.workItems.comment(n),transition:async(n)=>t.workItems.transition(n)},pullRequests:{list:async(n={})=>t.pullRequests.list(await gA(A.credentialProvider,n,"pullRequests.list"))},components:{list:async(n={})=>t.components.list(await gA(A.credentialProvider,n,"components.list")),get:async(n)=>t.components.get(n),register:async(n)=>t.components.register(await gA(A.credentialProvider,n,ZB.operationId)),deregister:async(n)=>t.components.deregister({componentId:n.componentId,...n.reason!==void 0?{reason:n.reason}:{}}),rename:async(n)=>t.components.rename(n),assignTeam:async(n)=>t.components.assignTeam(n),retirementPreview:async(n)=>t.components.retirementPreview(n),retire:async(n)=>t.components.retire(n),restorationPreview:async(n)=>t.components.restorationPreview(n),restore:async(n)=>t.components.restore(n),mergePreview:async(n)=>t.components.mergePreview(await gA(A.credentialProvider,n,"components.mergePreview")),merge:async(n)=>t.components.merge(await gA(A.credentialProvider,n,"components.merge")),relationships:{list:async(n={})=>t.components.relationships.list(await gA(A.credentialProvider,n,"components.relationships.list")),preview:async(n)=>t.components.relationships.preview(await gA(A.credentialProvider,n,"components.relationships.preview")),add:async(n)=>t.components.relationships.add(await gA(A.credentialProvider,n,"components.relationships.add")),remove:async(n)=>t.components.relationships.remove(await gA(A.credentialProvider,n,"components.relationships.remove"))},incidents:{list:async(n={})=>t.components.incidents.list(await gA(A.credentialProvider,n,"components.incidents.list"))},timeline:async(n)=>t.components.timeline(n)},billing:{getSummary:async(n={})=>t.billing.getSummary(await kA(A.credentialProvider,n)),getUsage:async(n={})=>t.billing.getUsage(await kA(A.credentialProvider,n)),listTransactions:async(n={})=>t.billing.listTransactions(await kA(A.credentialProvider,n)),previewSubscriptionCancellation:async(n={})=>t.billing.previewSubscriptionCancellation(await kA(A.credentialProvider,n)),scheduleSubscriptionCancellation:async(n={})=>t.billing.scheduleSubscriptionCancellation(await kA(A.credentialProvider,n)),resumeSubscriptionCancellation:async(n={})=>t.billing.resumeSubscriptionCancellation(await kA(A.credentialProvider,n)),getAutoTopUp:async(n={})=>t.billing.getAutoTopUp(await kA(A.credentialProvider,n)),updateAutoTopUp:async(n)=>t.billing.updateAutoTopUp(await kA(A.credentialProvider,n)),purchaseCredits:async(n)=>t.billing.purchaseCredits(await kA(A.credentialProvider,n)),listPlans:async(n={})=>t.billing.listPlans(await kA(A.credentialProvider,n)),previewPlanChange:async(n)=>t.billing.previewPlanChange(await kA(A.credentialProvider,n)),changePlan:async(n)=>t.billing.changePlan(await kA(A.credentialProvider,n)),createCheckoutSession:async(n)=>t.billing.createCheckoutSession(await kA(A.credentialProvider,n)),getCheckoutSessionStatus:async(n)=>t.billing.getCheckoutSessionStatus(await kA(A.credentialProvider,n)),createPortalSession:async(n={})=>t.billing.createPortalSession(await kA(A.credentialProvider,n)),getPaymentMethod:async(n={})=>t.billing.getPaymentMethod(await kA(A.credentialProvider,n))},tasks:{list:async(n={})=>t.tasks.list(await gA(A.credentialProvider,n,Ly.operationId))},recommendations:{list:async(n={})=>t.recommendations.list(await gA(A.credentialProvider,n,Ny.operationId))},repos:{list:async(n={})=>t.repos.list(await gA(A.credentialProvider,n,uy.operationId)),add:async(n)=>t.repos.add(await gA(A.credentialProvider,n,Uy.operationId)),remove:async(n)=>t.repos.remove(await gA(A.credentialProvider,n,Fy.operationId))},notificationDeliveryRules:{list:async(n={})=>t.notificationDeliveryRules.list(await gA(A.credentialProvider,n,"notificationDeliveryRules.list")),options:async(n={})=>t.notificationDeliveryRules.options(await gA(A.credentialProvider,n,"notificationDeliveryRules.options")),create:async(n)=>t.notificationDeliveryRules.create(await gA(A.credentialProvider,n,"notificationDeliveryRules.create")),update:async(n)=>t.notificationDeliveryRules.update(await gA(A.credentialProvider,n,"notificationDeliveryRules.update")),delete:async(n)=>t.notificationDeliveryRules.delete(await gA(A.credentialProvider,n,"notificationDeliveryRules.delete"))},notificationChannels:{getProject:async(n={})=>t.notificationChannels.getProject(await gA(A.credentialProvider,n,"notificationChannels.getProject"))}}},iO=async(A={})=>{let t=await zyA(A.fetch)(PyA(A.apiBaseUrl??JyA,"/device/code"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:A.clientId??TyA,...A.scope?{scope:A.scope}:{}})}),g=await t.json();if(!t.ok)throw PdA(g,t.status);let i=g;return{deviceCode:Ke(i.device_code,"device_code"),userCode:Ke(i.user_code,"user_code"),verificationUri:Ke(i.verification_uri,"verification_uri"),verificationUriComplete:Ke(i.verification_uri_complete,"verification_uri_complete"),expiresIn:nO(i.expires_in,"expires_in"),interval:nO(i.interval,"interval")}},QO=async(A)=>{let t=await zyA(A.fetch)(PyA(A.apiBaseUrl??JyA,"/device/token"),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({grant_type:SdA,device_code:A.deviceCode,client_id:A.clientId??TyA})}),g=await t.json();if(t.ok){let n=g;return{status:"authorized",accessToken:Ke(n.access_token,"access_token"),tokenType:Ke(n.token_type,"token_type"),expiresIn:nO(n.expires_in,"expires_in"),scope:typeof n.scope==="string"?n.scope:""}}let i=fyA(g);if(!i)throw Error(`Device authorization failed with status ${t.status}`);if(i.error==="authorization_pending")return{status:"pending"};if(i.error==="slow_down")return{status:"pending",interval:10};if(i.error==="access_denied")return{status:"denied",message:i.errorDescription};if(i.error==="expired_token"||i.error==="invalid_grant")return{status:"expired",message:i.errorDescription};throw Error(i.errorDescription)},ldA=(A)=>{let t=A.replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`},PyA=(A,t)=>{return`${A.replace(/\/+$/,"")}/api/auth${t}`},MdA=async(A,t)=>{return kA(A,t)},kA=async(A,t)=>{let g=t.organizationId??await A.getOrganizationId?.();return g?{...t,organizationId:g}:t},YdA=async(A,t)=>{let g=t.organizationId??await A.getOrganizationId?.();if(!g)throw new dt("BAD_REQUEST",{message:"Organization ID is required",data:{operationId:"organizations.update",missingContext:["organizationId"]},status:400});return{...t,organizationId:g}},$dA=async(A,t)=>{let g=t.projectId??await A.getProjectId?.();return g?{...t,projectId:g}:t},gA=async(A,t,g)=>{let i=t.projectId??await A.getProjectId?.();if(!i)throw new dt("BAD_REQUEST",{message:"Project ID is required",data:{operationId:g,missingContext:["projectId"]},status:400});return{...t,projectId:i}},kdA=async(A,t)=>{let g=t.projectId??await A.getProjectId?.();return g?{...t,projectId:g}:t},GdA=async(A,t)=>{let g=t.projectId??await A.getProjectId?.();return g?{...t,projectId:g}:t},JdA=async(A,t)=>{let g=t.projectId??await A.getProjectId?.();return g?{...t,projectId:g}:t},TdA=(A)=>{return{threadId:A.threadId,message:A.message,wait:A.wait??!0,timeoutSeconds:A.timeoutSeconds??20,...A.automationId!==void 0?{automationId:A.automationId}:{}}},RdA=(A)=>{if(!A||typeof A!=="object")return null;let t=A;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((g)=>typeof g==="string"):[],...typeof t.reason==="string"?{reason:t.reason}:{},...typeof t.retryAfterSeconds==="number"?{retryAfterSeconds:t.retryAfterSeconds}:{}}},fyA=(A)=>{if(!A||typeof A!=="object")return null;let t=A;if(typeof t.error!=="string"||typeof t.error_description!=="string")return null;return{error:t.error,errorDescription:t.error_description}},PdA=(A,t)=>{let g=fyA(A);return Error(g?.errorDescription??`Device authorization failed with status ${t}`)},zyA=(A)=>{return A??globalThis.fetch},GyA=(A,t)=>({result:t,poll:()=>A.runs.get({runId:t.runId}),waitForCompletion:async(g={})=>fdA(A,t,g)}),fdA=async(A,t,g)=>{if(t.completed)return t;let i=g.intervalMs??2000,n=Date.now(),Q=t;while(!Q.completed){if(g.timeoutMs!==void 0&&Date.now()-n>=g.timeoutMs)return Q;await zdA(i),Q=await A.runs.get({runId:Q.runId})}return Q},zdA=async(A)=>{await new Promise((t)=>globalThis.setTimeout(t,A))},Ke=(A,t)=>{if(typeof A==="string")return A;throw Error(`Expected '${t}' to be a string.`)},nO=(A,t)=>{if(typeof A==="number")return A;throw Error(`Expected '${t}' to be a number.`)};var oO=D(()=>{BB();Fv();HI();ryA();tO();tO()});var ut=(A)=>({success:!0,value:A}),wt=(A,t,g)=>({success:!1,error:A,...t!==void 0&&{statusCode:t},...g!==void 0&&{errorPayload:g}}),OdA=(A)=>{if(A===void 0)return"NETWORK_ERROR";if(A===401)return"UNAUTHORIZED";if(A===403)return"FORBIDDEN";if(A===404)return"NOT_FOUND";if(A===429)return"TOO_MANY_REQUESTS";if(A>=500)return"SERVER_ERROR";return"REQUEST_FAILED"},N=(A,t,g)=>{if(!A.success){let i=`${t}: ${A.error}`;if(g)return b(A.errorPayload??{code:OdA(A.statusCode),message:i,operationId:null});return r(i)}return A.value};var IA=D(()=>{nA()});var vdA="https://api.sazabi.com",k=async(A)=>{try{return ut(await A())}catch(t){let g=ZdA(t),i=WdA(t),n=t instanceof Error?t.message:String(t);if(g?.retryAfterSeconds!==void 0)n+=` Retry in ~${g.retryAfterSeconds}s.`;return wt(n,i,g)}},ZdA=(A)=>{if(!A||typeof A!=="object")return;let t=A;if(typeof t.code!=="string"||typeof t.message!=="string"||!t.data||typeof t.data!=="object")return;let g=t.data;if(typeof g.operationId!=="string")return;return{code:t.code,message:t.message,operationId:g.operationId,...typeof g.reason==="string"?{reason:g.reason}:{},...typeof g.retryAfterSeconds==="number"?{retryAfterSeconds:g.retryAfterSeconds}:{},...Array.isArray(g.missingContext)?{missingContext:g.missingContext.filter((i)=>typeof i==="string")}:{}}},WdA=(A)=>{if(!A||typeof A!=="object")return;let t=A;return typeof t.status==="number"?t.status:void 0},CQ=(A)=>{let t=RyA({apiBaseUrl:A.baseUrl??vdA,clientSource:"cli",sandboxActorDescriptor:A.sandboxActorDescriptor,credentialProvider:{getToken:()=>A.token,getOrganizationId:()=>A.organizationId,getProjectId:()=>A.projectId},intakeBaseUrl:A.intakeBaseUrl,tailBaseUrl:A.tailBaseUrl});return{me:()=>k(()=>t.me()),automations:{list:(g={})=>k(()=>t.automations.list(g)),get:(g)=>k(()=>t.automations.get({automationId:g})),create:(g)=>k(()=>t.automations.create(g)),update:(g)=>k(()=>t.automations.update(g)),enable:(g)=>k(()=>t.automations.enable({automationId:g})),disable:(g)=>k(()=>t.automations.disable({automationId:g})),runs:{list:(g,i={})=>k(()=>t.automations.runs.list({automationId:g,...i})),get:(g,i)=>k(()=>t.automations.runs.get({automationId:g,runId:i})),logs:(g,i)=>k(()=>t.automations.runs.logs({automationId:g,runId:i}))}},logs:{tail:(g)=>k(()=>t.logs.tail(g)),forward:(g)=>k(()=>t.logs.forward(g)),query:(g={})=>k(()=>t.logs.query(g)),schema:(g={})=>k(()=>t.logs.schema(g)),volume:(g)=>k(()=>t.logs.volume(g)),patterns:(g={})=>k(()=>t.logs.patterns(g)),nativeQuery:(g)=>k(()=>t.logs.nativeQuery(g))},organizations:{list:()=>k(()=>t.organizations.list()),get:(g)=>k(()=>t.organizations.get({organizationId:g})),create:(g)=>k(()=>t.organizations.create({name:g})),rename:(g,i)=>k(()=>t.organizations.update({organizationId:i,name:g}))},members:{list:(g={})=>k(()=>t.members.list(g)),updateRole:(g,i,n)=>k(()=>t.members.updateRole({organizationId:n,member:g,role:i})),remove:(g,i)=>k(()=>t.members.remove({organizationId:i,member:g})),invite:(g)=>k(()=>t.members.invite({organizationId:g.organizationId,email:g.email,role:g.role})),listInvitations:(g)=>k(()=>t.members.listInvitations({organizationId:g})),revokeInvitation:(g)=>k(()=>t.members.revokeInvitation({organizationId:g.organizationId,invitationId:g.invitationId}))},teams:{list:(g={})=>k(()=>t.teams.list(g)),create:(g,i,n)=>k(()=>t.teams.create({organizationId:n,name:g,...i!==void 0?{description:i}:{}})),update:(g,i,n)=>k(()=>t.teams.update({organizationId:n,teamId:g,...i.name!==void 0?{name:i.name}:{},...i.description!==void 0?{description:i.description}:{}})),delete:(g,i)=>k(()=>t.teams.delete({organizationId:i,teamId:g})),addMember:(g,i,n)=>k(()=>t.teams.addMember({organizationId:n,teamId:g,userId:i})),removeMember:(g,i,n)=>k(()=>t.teams.removeMember({organizationId:n,teamId:g,userId:i})),listMembers:(g,i)=>k(()=>t.teams.listMembers({organizationId:i,teamId:g}))},projects:{list:(g={})=>k(()=>t.projects.list(g)),get:(g)=>k(()=>t.projects.get({projectId:g})),create:(g)=>k(()=>t.projects.create(g))},threads:{list:(g={})=>k(()=>t.threads.list(g)),get:(g)=>k(()=>t.threads.get({threadId:g})),create:(g)=>k(()=>t.threads.create(g)),getStatus:(g)=>k(()=>t.threads.getStatus({threadId:g})),update:(g,i)=>k(()=>t.threads.update({threadId:g,status:i})),fork:(g,i)=>k(()=>t.threads.fork({threadId:g,messageId:i})),setVisibility:(g,i)=>k(()=>t.threads.setVisibility({threadId:g,visibility:i})),createShareLink:(g)=>k(()=>t.threads.createShareLink({threadId:g})),listShareLinks:(g)=>k(()=>t.threads.listShareLinks({threadId:g})),revokeShareLink:(g,i)=>k(()=>t.threads.revokeShareLink({threadId:g,shareId:i})),stop:(g)=>k(()=>t.threads.stop({threadId:g})),stream:(g)=>k(()=>t.threads.stream(g))},messages:{list:(g,i={})=>k(()=>t.messages.list({threadId:g,...i})),append:(g,i,n,Q,o,B)=>k(()=>t.messages.append({threadId:g,message:i,wait:n,timeoutSeconds:Q,...o!==void 0?{automationId:o}:{},...B?{ambientServiceRun:B}:{}}))},runs:{get:(g)=>k(()=>t.runs.get({runId:g})),cancel:(g)=>k(()=>t.runs.cancel({runId:g})),stream:(g)=>k(()=>t.runs.stream(g))},search:{threads:(g)=>k(()=>t.search.threads(g)),messages:(g)=>k(()=>t.search.messages(g))},publicKeys:{list:(g)=>k(()=>t.publicKeys.list(g)),get:(g,i)=>k(()=>t.publicKeys.get(i?{keyId:g,projectId:i}:{keyId:g})),ensureLogForwarding:(g)=>k(()=>t.publicKeys.ensureLogForwarding(g)),update:(g)=>k(()=>t.publicKeys.update(g)),deactivate:(g)=>k(()=>t.publicKeys.deactivate(g))},secretKeys:{list:(g)=>k(()=>t.secretKeys.list(g)),get:(g)=>k(()=>t.secretKeys.get({keyId:g})),create:(g)=>k(()=>t.secretKeys.create(g)),update:(g)=>k(()=>t.secretKeys.update(g)),delete:(g)=>k(()=>t.secretKeys.delete(g))},issues:{count:(g={})=>k(()=>t.issues.count(g)),create:(g)=>k(()=>t.issues.create(g)),list:(g={})=>k(()=>t.issues.list(g)),search:(g={})=>k(()=>t.issues.search(g)),get:(g)=>k(()=>t.issues.get({issueId:g})),resolve:(g)=>k(()=>t.issues.resolve({issueId:g})),ignore:(g)=>k(()=>t.issues.ignore({issueId:g})),reopen:(g)=>k(()=>t.issues.reopen({issueId:g})),mute:(g)=>k(()=>t.issues.mute({issueId:g})),unmute:(g)=>k(()=>t.issues.unmute({issueId:g}))},pullRequests:{list:(g={})=>k(()=>t.pullRequests.list(g))},workItems:{create:(g)=>k(()=>t.workItems.create(g)),comment:(g)=>k(()=>t.workItems.comment(g)),transition:(g)=>k(()=>t.workItems.transition(g))},components:{list:(g={})=>k(()=>t.components.list(g)),get:(g)=>k(()=>t.components.get({componentId:g})),register:(g)=>k(()=>t.components.register(g)),deregister:(g,i)=>k(()=>t.components.deregister({componentId:g,...i!==void 0?{reason:i}:{}})),rename:(g)=>k(()=>t.components.rename(g)),retirementPreview:(g)=>k(()=>t.components.retirementPreview(g)),retire:(g)=>k(()=>t.components.retire(g)),restorationPreview:(g)=>k(()=>t.components.restorationPreview(g)),restore:(g)=>k(()=>t.components.restore(g)),mergePreview:(g)=>k(()=>t.components.mergePreview(g)),merge:(g)=>k(()=>t.components.merge(g)),relationships:{list:(g={})=>k(()=>t.components.relationships.list(g)),preview:(g)=>k(()=>t.components.relationships.preview(g)),add:(g)=>k(()=>t.components.relationships.add(g)),remove:(g)=>k(()=>t.components.relationships.remove(g))},incidents:{list:(g={})=>k(()=>t.components.incidents.list(g))},timeline:(g)=>k(()=>t.components.timeline(g))},billing:{getSummary:(g={})=>k(()=>t.billing.getSummary(g)),getUsage:(g={})=>k(()=>t.billing.getUsage(g)),listTransactions:(g={})=>k(()=>t.billing.listTransactions(g)),previewSubscriptionCancellation:()=>k(()=>t.billing.previewSubscriptionCancellation()),scheduleSubscriptionCancellation:()=>k(()=>t.billing.scheduleSubscriptionCancellation()),resumeSubscriptionCancellation:()=>k(()=>t.billing.resumeSubscriptionCancellation()),getAutoTopUp:(g={})=>k(()=>t.billing.getAutoTopUp(g)),updateAutoTopUp:(g)=>k(()=>t.billing.updateAutoTopUp(g)),purchaseCredits:(g)=>k(()=>t.billing.purchaseCredits(g)),listPlans:(g={})=>k(()=>t.billing.listPlans(g)),previewPlanChange:(g)=>k(()=>t.billing.previewPlanChange(g)),changePlan:(g)=>k(()=>t.billing.changePlan(g)),createCheckoutSession:(g)=>k(()=>t.billing.createCheckoutSession(g)),getCheckoutSessionStatus:(g)=>k(()=>t.billing.getCheckoutSessionStatus(g)),createPortalSession:(g={})=>k(()=>t.billing.createPortalSession(g)),getPaymentMethod:(g={})=>k(()=>t.billing.getPaymentMethod(g))},tasks:{list:(g={})=>k(()=>t.tasks.list(g))},recommendations:{list:(g={})=>k(()=>t.recommendations.list(g))},repos:{list:(g={})=>k(()=>t.repos.list(g)),add:(g)=>k(()=>t.repos.add(g)),remove:(g)=>k(()=>t.repos.remove(g))},onboarding:{getState:(g={})=>k(()=>t.onboarding.getState(g)),skipSampleIssue:(g)=>k(()=>t.onboarding.skipSampleIssue(g)),finish:(g)=>k(()=>t.onboarding.finish(g))},notificationDeliveryRules:{list:()=>k(()=>t.notificationDeliveryRules.list()),options:()=>k(()=>t.notificationDeliveryRules.options()),create:(g)=>k(()=>t.notificationDeliveryRules.create(g)),update:(g)=>k(()=>t.notificationDeliveryRules.update(g)),delete:(g)=>k(()=>t.notificationDeliveryRules.delete({ruleId:g}))},notificationChannels:{getProject:()=>k(()=>t.notificationChannels.getProject())},logSources:{listProviders:()=>k(()=>t.logSources.listProviders()),list:(g)=>k(()=>t.logSources.list(g)),get:(g)=>k(()=>t.logSources.get({logSourceId:g})),create:(g)=>k(()=>t.logSources.create(g)),update:(g)=>k(()=>t.logSources.update(g)),delete:(g)=>k(()=>t.logSources.delete({logSourceId:g}))},logStreams:{list:(g)=>k(()=>t.logStreams.list({logSourceId:g})),get:(g)=>k(()=>t.logStreams.get({streamId:g})),create:(g)=>k(()=>t.logStreams.create(g)),update:(g)=>k(()=>t.logStreams.update(g)),delete:(g)=>k(()=>t.logStreams.delete({streamId:g})),reassign:(g)=>k(()=>t.logStreams.reassign(g))},integrations:{listProviders:()=>k(()=>t.integrations.listProviders()),listConnections:(g)=>k(()=>t.integrations.listConnections(g)),getConnection:(g)=>k(()=>t.integrations.getConnection({connectionId:g})),createConnection:(g)=>k(()=>t.integrations.createConnection(g)),beginConnect:(g)=>k(()=>t.integrations.beginConnect(g)),getConnectAttempt:(g)=>k(()=>t.integrations.getConnectAttempt({attemptId:g})),disconnectConnection:(g)=>k(()=>t.integrations.disconnectConnection({connectionId:g})),updateConnectionCredentials:(g)=>k(()=>t.integrations.updateConnectionCredentials(g))},connectedAccounts:{beginConnect:(g)=>k(()=>t.connectedAccounts.beginConnect(g)),getConnectAttempt:(g)=>k(()=>t.connectedAccounts.getConnectAttempt({attemptId:g})),list:()=>k(()=>t.connectedAccounts.list({})),disconnect:(g)=>k(()=>t.connectedAccounts.disconnect(g))},mcpConnectors:{list:(g)=>k(()=>t.mcpConnectors.list(g)),get:(g)=>k(()=>t.mcpConnectors.get(g)),details:(g)=>k(()=>t.mcpConnectors.details(g)),listProviders:()=>k(()=>t.mcpConnectors.listProviders()),beginOAuthInstall:(g)=>k(()=>t.mcpConnectors.beginOAuthInstall(g)),getOAuthInstallAttempt:(g)=>k(()=>t.mcpConnectors.getOAuthInstallAttempt(g)),disconnect:(g)=>k(()=>t.mcpConnectors.disconnect(g)),update:(g)=>k(()=>t.mcpConnectors.update(g))},sandboxPresets:{delete:(g)=>k(()=>t.sandboxPresets.delete(g)),listConnections:(g)=>k(()=>t.sandboxPresets.listConnections(g)),listTypes:()=>k(()=>t.sandboxPresets.listTypes()),test:(g)=>k(()=>t.sandboxPresets.test(g)),upsert:(g)=>k(()=>t.sandboxPresets.upsert(g))},memory:{list:(g={})=>k(()=>t.memory.list(g)),get:(g)=>k(()=>t.memory.get(g)),search:(g)=>k(()=>t.memory.search(g)),put:(g)=>k(()=>t.memory.put({kind:"note",...g})),delete:(g)=>k(()=>t.memory.delete(g))},logMatchExpressions:{list:(g={})=>k(()=>t.logMatchExpressions.list(g)),get:(g)=>k(()=>t.logMatchExpressions.get({expressionId:g})),create:(g)=>k(()=>t.logMatchExpressions.create(g)),update:(g,i={})=>k(()=>t.logMatchExpressions.update({expressionId:g,...i})),disable:(g)=>k(()=>t.logMatchExpressions.disable({expressionId:g}))},scripts:{list:(g={})=>k(()=>t.scripts.list(g)),get:(g)=>k(()=>t.scripts.get({name:g})),create:(g)=>k(()=>t.scripts.create(g)),update:(g,i={})=>k(()=>t.scripts.update({name:g,...i})),delete:(g)=>k(()=>t.scripts.delete({name:g}))}}};var Sy=D(()=>{oO();IA()});var OyA;var vyA=D(()=>{OyA={version:2,activeProfile:"default",profiles:{default:{}}}});import*as cQ from"node:fs";import*as ZyA from"node:os";import*as hO from"node:path";var bg=(A)=>{if(A===void 0||A===null)return;if(typeof A==="string")return A.length>0?A:void 0;return},VdA=(A)=>{if(typeof A!=="object"||A===null||Array.isArray(A))return;let t={};for(let[g,i]of Object.entries(A)){if(!Array.isArray(i))continue;let n=i.filter((Q)=>typeof Q==="string"&&Q.length>0);if(n.length>0)t[g]=n}return Object.keys(t).length>0?t:void 0},IO,je,XdA=()=>{if(!cQ.existsSync(IO))cQ.mkdirSync(IO,{recursive:!0,mode:448})},BO,WyA=(A)=>{BO=A},VyA=(A)=>({token:bg(A.token),activeOrganizationId:bg(A.activeOrganizationId??A.organizationId),organizationName:bg(A.organizationName),activeProjectId:bg(A.activeProjectId??A.defaultProjectId),apiBaseUrl:bg(A.apiBaseUrl),authBaseUrl:bg(A.authBaseUrl),webBaseUrl:bg(A.webBaseUrl),intakeBaseUrl:bg(A.intakeBaseUrl),tailBaseUrl:bg(A.tailBaseUrl),apiDomain:bg(A.apiDomain),webDomain:bg(A.webDomain),intakeDomain:bg(A.intakeDomain),tailDomain:bg(A.tailDomain),forwardPublicKey:bg(A.forwardPublicKey),forwardPublicKeyProjectId:bg(A.forwardPublicKeyProjectId),skippedOnboardingSteps:VdA(A.skippedOnboardingSteps)}),HdA=(A)=>({version:2,activeProfile:"default",profiles:{default:VyA(A)}}),KdA=(A)=>{let t=bg(A.activeProfile)??"default",g=typeof A.profiles==="object"&&A.profiles!==null?A.profiles:{},i={};for(let[n,Q]of Object.entries(g)){if(typeof Q!=="object"||Q===null)continue;i[n]=VyA(Q)}if(!i[t])i[t]={};return{version:2,activeProfile:t,profiles:i}},mA=()=>{try{if(!cQ.existsSync(je))return ut(OyA);let A=cQ.readFileSync(je,"utf-8"),t=JSON.parse(A),g=typeof t.version==="number"?t.version:void 0;if(g!==void 0&&g>2)return wt("Settings file requires a newer CLI version. Upgrade with 'npm install -g @sazabi/cli@latest'.");if(g===2)return ut(KdA(t));let i=HdA(t),n=at(i);if(!n.success)return n;return ut(i)}catch(A){let t=A instanceof Error?A.message:String(A);return wt(t)}},at=(A)=>{try{return XdA(),cQ.writeFileSync(je,JSON.stringify(A,null,2),{encoding:"utf-8",mode:384}),ut(void 0)}catch(t){let g=t instanceof Error?t.message:String(t);return wt(g)}},zn=(A,t)=>{if(t)return t;if(BO)return BO;let g=process.env.SAZABI_PROFILE?.trim();if(g)return g;return A.activeProfile??"default"},mt=(A,t)=>{let g=zn(A,t),i=A.profiles[g];if(i)return ut(i);if(g==="default")return ut({});return wt(`Profile '${g}' does not exist. Run 'sazabi profiles create ${g}' first.`)},oi=()=>{let A=mA();if(!A.success)return A;return mt(A.value)},xt=(A,t,g)=>{let i=zn(A,g);if(!A.profiles[i])return wt(`Profile '${i}' does not exist. Run 'sazabi profiles create ${i}' first.`);return ut({...A,profiles:{...A.profiles,[i]:{...A.profiles[i],...t}}})},XyA=(A,t)=>A?.skippedOnboardingSteps?.[t]??[],HyA=(A,t,g,i)=>{let n=mt(A,i);if(!n.success)return n;let Q={...n.value.skippedOnboardingSteps},o=Q[t]??[];if(!o.includes(g))Q[t]=[...o,g];return xt(A,{skippedOnboardingSteps:Q},i)},KyA=(A,t,g)=>{let i=mt(A,g);if(!i.success)return i;let{[t]:n,...Q}=i.value.skippedOnboardingSteps??{};return xt(A,{skippedOnboardingSteps:Object.keys(Q).length>0?Q:void 0},g)},On=(A)=>{if(!A?.forwardPublicKey&&!A?.forwardPublicKeyProjectId)return{};return{forwardPublicKey:void 0,forwardPublicKeyProjectId:void 0}};var Ng=D(()=>{vyA();IA();IO=hO.join(ZyA.homedir(),".sazabi"),je=hO.join(IO,"settings.json")});var fi=(A)=>{let{cliFlag:t,globalUrl:g,globalDomain:i,buildUrlFromDomain:n,defaultUrl:Q}=A;if(t)return t;let o=process.env.SAZABI_API_URL?.trim();if(o)return o;if(g)return g;if(i)return n(i);return Q},P=(A)=>{let{tokenFlag:t,organizationIdFlag:g,projectIdFlag:i,jsonMode:n}=A,Q=t?.trim(),o=process.env.SAZABI_TOKEN?.trim(),B=process.env.SAZABI_ORGANIZATION_ID?.trim(),h=process.env.SAZABI_PROJECT_ID?.trim(),e=N(oi(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",n),C=e.token?.trim(),c=(Q&&Q.length>0?Q:void 0)||(o&&o.length>0?o:void 0)||C,E=Q&&Q.length>0?"flag":o&&o.length>0?"environment":"settings";if(!c||c.length===0){if(n)return b("Not authenticated. Set SAZABI_TOKEN, pass --token, run 'sazabi auth login', or run 'sazabi auth save <token>'.");return r("Not authenticated. Set SAZABI_TOKEN, pass --token, run 'sazabi auth login', or run 'sazabi auth save <token>'.")}let y,w;if(g)y=g,w="flag";else if(B&&B.length>0)y=B,w="environment";else if(e.activeOrganizationId)y=e.activeOrganizationId,w="settings";let a,u;if(i)a=i,u="flag";else if(h&&h.length>0)a=h,u="environment";else if(e.activeProjectId)a=e.activeProjectId,u="settings";return{token:c,type:"token",projectId:a,organizationId:y,tokenSource:E,organizationSource:w,projectSource:u}},ly=(A)=>{let t=N(oi(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",A?.jsonMode);return fi({cliFlag:A?.apiBaseUrlFlag,globalUrl:t.apiBaseUrl,globalDomain:t.apiDomain,buildUrlFromDomain:(g)=>`https://api.${g}`,defaultUrl:"https://api.sazabi.com"})},z=(A)=>{let t=ly({apiBaseUrlFlag:A.apiBaseUrlFlag,jsonMode:A.jsonMode});return CQ({token:A.token,baseUrl:t,organizationId:A.organizationId,projectId:A.projectId,sandboxActorDescriptor:process.env.SAZABI_SANDBOX_ACTOR})},jyA,eO,bN=async(A)=>{let t=N(oi(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",A.jsonMode),g=fi({cliFlag:A.apiBaseUrlFlag,globalUrl:t.apiBaseUrl,globalDomain:t.apiDomain,buildUrlFromDomain:(h)=>`https://api.${h}`,defaultUrl:"https://api.sazabi.com"}),i=`${A.token}@${g}@${A.projectId??""}`,n=jyA.get(i);if(n)return n;let Q=eO.get(i);if(Q)return Q;if(!A.projectId){if(A.jsonMode)return b("Project ID is required. Run 'sazabi projects use <project-id>' or set SAZABI_PROJECT_ID.");return r("Project ID is required. Run 'sazabi projects use <project-id>' or set SAZABI_PROJECT_ID.")}let o=A.projectId,B=(async()=>{let e=await CQ({token:A.token,baseUrl:g,projectId:o}).projects.get(o),c=N(e,"Couldn't fetch project info (run 'sazabi projects list' to verify the project ID)",A.jsonMode).project;return jyA.set(i,c),c})();eO.set(i,B);try{return await B}finally{eO.delete(i)}},rN=(A)=>{let t=A.trim().toLowerCase(),g=/^[a-z][a-z0-9+.-]*:\/\//.test(t)?t:`https://${t}`,i=t;try{i=new URL(g).hostname.toLowerCase()}catch{i=t.replace(/^[a-z][a-z0-9+.-]*:\/\//,"").replace(/[/?#].*$/,"").replace(/:\d+$/,"")}return`https://app.${i.replace(/^(?:app\.)+/,"")}`},jdA=(A)=>{try{let t=new URL(A),g=t.hostname.toLowerCase();if(!g.startsWith("api."))return null;return`${t.protocol}//app.${g.slice(4)}`}catch{return null}},zi=(A)=>{let t=(i)=>i.replace(/\/+$/,"");if(A)return t(A);let g=N(oi(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)");if(g.webBaseUrl)return t(g.webBaseUrl);if(g.webDomain)return rN(g.webDomain);if(g.apiDomain)return rN(g.apiDomain);if(g.apiBaseUrl){let i=jdA(g.apiBaseUrl);if(i)return i}return"https://app.sazabi.com"},dg=(A,t)=>{if(A&&A.length>0)return A;let g="No project selected. Pass --project-id, set SAZABI_PROJECT_ID, or run 'sazabi projects use <project-id>'.";if(t)return b(g);return r(g)},uo=(A,t)=>{return`${zi(t)}/projects/${A}`},Ot=(A,t,g,i)=>{let n=`${zi(g)}/projects/${A}/threads/${t}`;return i?`${n}?messageId=${encodeURIComponent(i)}`:n},_yA=(A,t,g,i)=>{return Ot(A,t,g,i)},myA=(A,t,g)=>{return`${uo(A,g)}/issues/${t}`},xyA=(A,t,g)=>{return`${uo(A,g)}/automations/${t}`},qyA=(A,t)=>{return`${uo(A,t)}/status`},dyA=(A,t,g)=>{return`${uo(A,g)}/settings/log-source-providers/${t}`},pyA=(A,t,g)=>{return`${uo(A,g)}/settings/mcp-connectors/${t}`},NN=(A,t,g)=>{return`${uo(A,g)}/settings/sandbox/catalog/${t}`},syA=(A,t)=>{return`https://otlp.${t}.intake.${A}`};var aA=D(()=>{nA();Sy();IA();Ng();jyA=new Map,eO=new Map});var dN,ebA=(A)=>{dN.set(A.name,A)},pN=(A)=>{return dN.get(A)},dy=()=>{return Array.from(dN.values())},CbA=(A)=>{return dN.has(A)};var F1=D(()=>{dN=new Map});async function Y1(A){let t=await A.publicKeys.list({limit:20});if(!t.success)return[];return t.value.publicKeys.map((g)=>({value:g.id,description:g.name}))}async function $1(A){let t=await A.secretKeys.list({limit:20});if(!t.success)return[];return t.value.secretKeys.map((g)=>({value:g.id,description:g.name}))}async function sy(A){let t=await A.logSources.list();if(!t.success)return[];return t.value.logSources.map((g)=>({value:g.id,description:g.name??g.provider}))}async function EbA(A){let t=await A.members.list();if(!t.success)return[];return t.value.members.map((g)=>({value:g.userId,description:g.name??g.email}))}var _ot=3000,mot,ybA=async(A,t,g)=>{try{let i=mot[A]?.[t];if(!i)return[];let n=oi();if(!n.success)return[];let Q=n.value,o=process.env.SAZABI_TOKEN?.trim()||Q.token?.trim();if(!o)return[];let B=fi({globalUrl:Q.apiBaseUrl,globalDomain:Q.apiDomain,buildUrlFromDomain:(C)=>`https://api.${C}`,defaultUrl:"https://api.sazabi.com"}),h=CQ({token:o,baseUrl:B,organizationId:Q.activeOrganizationId,projectId:Q.activeProjectId});return(await Promise.race([i(h),new Promise((C)=>setTimeout(()=>C([]),_ot))])).filter((C)=>C.value.startsWith(g))}catch{return[]}};var DbA=D(()=>{Sy();aA();Ng();mot={threads:{get:async(A)=>{let t=await A.threads.list({limit:20});if(!t.success)return[];return t.value.threads.map((g)=>({value:g.id,description:g.title??void 0}))}},projects:{use:async(A)=>{let t=await A.projects.list();if(!t.success)return[];return t.value.projects.map((g)=>({value:g.id,description:g.name}))}},organizations:{use:async(A)=>{let t=await A.organizations.list();if(!t.success)return[];return t.value.organizations.map((g)=>({value:g.id,description:g.name}))},rename:async(A)=>{let t=await A.organizations.list();if(!t.success)return[];return t.value.organizations.map((g)=>({value:g.id,description:g.name}))}},"public-keys":{get:Y1,update:Y1,deactivate:Y1},"secret-keys":{get:$1,update:$1,delete:$1},"log-sources":{get:sy,enable:sy,disable:sy,delete:sy,remove:sy},members:{"update-role":EbA,remove:EbA}}});var abA={};Bi(abA,{parseCompletionContext:()=>dot,getCompletions:()=>pot});var xot,qot,dot=(A)=>{let t=A.length>0?A:[""],g=t.length-1,i=t[g]??"";return{words:t,currentIndex:g,partial:i}},pot=async(A)=>{let{words:t,currentIndex:g,partial:i}=A,n=t[g-1];if(n==="--profile")return gIt(i);let Q=tIt(t),o=Math.max(0,Q.length-(t.length-g));if(o===0)return sot(i);let B=Q[0]??"",h=pN(B);if(!h)return[];if(o===1&&h.subcommands){if(i.startsWith("-"))return wbA(h.options,Q);return AIt(h,i)}let e=h.subcommands?Q[1]:void 0,c=(e?h.subcommands?.[e]:void 0)?.options??h.options;if(i.startsWith("-"))return wbA(c,Q);if(n?.startsWith("--")){let E=n.slice(2);if(c?.[E]?.type==="string"){let w=`${B}:${e??""}`,a=qot[w]?.[E]??xot[E];if(a)return a.filter((u)=>u.startsWith(i)).map((u)=>({value:u}));return[]}}return ybA(B,e??"",i)},sot=(A)=>{let g=dy().filter((n)=>n.name.startsWith(A)).map((n)=>({value:n.name,description:n.description})),i=[{value:"--help",description:"Show help"},{value:"--version",description:"Show version"},{value:"--profile",description:"Use a named profile"}];for(let n of i)if(n.value.startsWith(A))g.push(n);return g},AIt=(A,t)=>{if(!A.subcommands)return[];return Object.values(A.subcommands).filter((g)=>g.name.startsWith(t)).map((g)=>({value:g.name,description:g.description}))},wbA=(A,t)=>{let g=t[t.length-1]??"",i=new Set(t.filter((Q)=>Q.startsWith("--")).map((Q)=>Q.replace(/=.*/,""))),n=[];if(!i.has("--help")&&"--help".startsWith(g))n.push({value:"--help",description:"Show help"});if(!i.has("--profile")&&"--profile".startsWith(g))n.push({value:"--profile",description:"Use a named profile"});if(!A)return n;for(let[Q,o]of Object.entries(A)){let B=`--${Q}`;if(i.has(B))continue;if(!B.startsWith(g))continue;n.push({value:B,description:o.description})}return n},tIt=(A)=>{let t=[];for(let g=0;g<A.length;g++){let i=A[g];if(i==="--profile"&&g+1<A.length)g++;else if(i.startsWith("--profile="));else t.push(i)}return t},gIt=(A)=>{try{let t=mA();if(!t.success)return[];return Object.keys(t.value.profiles).filter((g)=>g.startsWith(A)).map((g)=>({value:g,description:g===t.value.activeProfile?"active":void 0}))}catch{return[]}};var rbA=D(()=>{F1();Ng();DbA();xot={status:["regular","archived"],format:["json","text"]},qot={"members:update-role":{role:["admin","member"]},"messages:search":{role:["user","assistant"]},"messages:list":{role:["user","assistant"]}}});nA();nA();nA();import{parseArgs as X1}from"node:util";var S=(A,t,g={})=>{let i=Object.hasOwn(t,"json")&&A.includes("--json"),n=(C,c)=>{if(i)b({code:C,message:c,operationId:null});throw r(c),Error("Unreachable")},Q=(()=>{try{return X1({args:A,options:t,allowPositionals:Boolean(g.allowPositionals),strict:!1,tokens:!0})}catch(C){let c=new Set(Object.keys(t)),E=new Set(Object.values(t).map((w)=>w.short).filter((w)=>Boolean(w)));try{let w=X1({args:A,options:t,allowPositionals:!0,strict:!1,tokens:!0}),a=[...new Set((w.tokens??[]).flatMap((u)=>u.kind==="option"?[u]:[]).filter((u)=>!c.has(u.name)&&!(u.name.length===1&&E.has(u.name))).map((u)=>u.name.length>1?`--${u.name}`:`-${u.name}`))];if(a.length>0)return n("UNEXPECTED_ARGUMENT",`Unknown option${a.length>1?"s":""}: ${a.join(", ")}. Run the command with -h for usage.`)}catch{}let y=C instanceof Error?C.message:"Invalid arguments.";return n("INVALID_ARGUMENT",`${y.endsWith(".")?y:`${y}.`} Run the command with -h for usage.`)}})(),o=Object.hasOwn(t,"json")&&Q.values.json===!0,B=new Set(Object.keys(t)),h=new Set(Object.entries(t).map(([,C])=>C.short).filter((C)=>Boolean(C))),e=[];if(Array.isArray(Q.tokens))for(let C of Q.tokens){if(C.kind!=="option")continue;let c=C.name,E=c.length>1;if(!(B.has(c)||!E&&h.has(c))){let w=E?`--${c}`:`-${c}`;if(!e.includes(w))e.push(w)}}for(let C of Object.keys(Q.values))if(!B.has(C)){let c=C.length>1?`--${C}`:`-${C}`;if(!e.includes(c))e.push(c)}if(e.length>0){let C=`Unknown option${e.length>1?"s":""}: ${e.join(", ")}. Run the command with -h for usage.`;if(o)b({code:"UNEXPECTED_ARGUMENT",message:C,operationId:null});r(C)}for(let[C,c]of Object.entries(t))if(c.type==="string"&&Q.values[C]===!0){let E=C.length===1?`-${C}`:`--${C}`,y=`Option ${E} requires a value. Use '${E} <value>'.`;n("INVALID_ARGUMENT",y)}for(let[C,c]of Object.entries(t)){let E=Q.values[C];if(c.type==="string"&&typeof E==="string"){if(E.length===0){let w=C.length===1?`-${C}`:`--${C}`;n("INVALID_ARGUMENT",`Option ${w} requires a non-empty value.`)}if(E.startsWith("--")||E.length===2&&E[0]==="-"&&/[a-zA-Z]/.test(E.charAt(1))){let a=`Option ${C.length===1?`-${C}`:`--${C}`} received "${E}" as its value. Did you forget to provide a value?`;n("INVALID_ARGUMENT",a)}}}if(!g.allowPositionals&&Q.positionals.length>0)n("UNEXPECTED_ARGUMENT",`Unexpected argument${Q.positionals.length>1?"s":""}: ${Q.positionals.join(", ")}. Run the command with -h for usage.`);return{values:Q.values,positionals:Q.positionals}};var oD=(A,t)=>{if(A?.json?.type!=="boolean")throw Error(`${t} must include a boolean --json option (enforced by CommandBuilder)`)};class H1{name;description;handler;subcommands;options;examples;positionalArgs;allowNoJson=!1;constructor(A,t,g){this.name=A,this.description=t,this.handler=g}withOptions(A){return this.options=A,this}withSubcommands(A){return this.subcommands=A,this}withExamples(A){return this.examples=A,this}withPositionalArgs(A){return this.positionalArgs=A,this}build(){if(!this.handler&&!this.subcommands)throw Error(`Subcommand "${this.name}" must have either a handler or subcommands`);if(!this.allowNoJson&&this.handler)oD(this.options,`Subcommand "${this.name}"`);if(!this.allowNoJson&&this.subcommands){for(let[A,t]of Object.entries(this.subcommands))if(!t.subcommands)oD(t.options,`Subcommand "${this.name} ${A}"`)}return{name:this.name,description:this.description,handler:this.handler,subcommands:this.subcommands,options:this.options,examples:this.examples,positionalArgs:this.positionalArgs}}allowWithoutJson(){return this.allowNoJson=!0,this}}class K1{name;description;handler;subcommands;options;examples;positionalArgs;allowNoJson=!1;constructor(A,t){this.name=A,this.description=t}withHandler(A){return this.handler=A,this}withSubcommands(A){return this.subcommands=A,this}withOptions(A){return this.options=A,this}withExamples(A){return this.examples=A,this}withPositionalArgs(A){return this.positionalArgs=A,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)oD(this.options,`Command "${this.name}"`);if(this.subcommands)for(let[A,t]of Object.entries(this.subcommands)){if(t.subcommands)continue;oD(t.options,`Subcommand "${this.name} ${A}"`)}}return{name:this.name,description:this.description,handler:this.handler,subcommands:this.subcommands,options:this.options,examples:this.examples,positionalArgs:this.positionalArgs}}allowWithoutJson(){return this.allowNoJson=!0,this}}var QA=(A,t)=>{return new K1(A,t)},U=(A,t,g)=>{return new H1(A,t,g)};nA();var Cg=(A,t,g,i,n)=>{let Q=Number.parseInt(A,10);if(Number.isNaN(Q)||Q<t||Q>g){let o=`${i} must be between ${t} and ${g}.`;if(n)return b(o);return r(o)}return Q},An=(A,t,g,i)=>{if(!t.includes(A)){let n=t.map((o)=>`"${o}"`).join(" or "),Q=`${g} must be ${n}.`;if(i)return b(Q);return r(Q)}return A};nA();aA();IA();var cO=(A)=>{let t=[];for(let g of A){let i=0;for(let n of g.content){if(n.type!=="artifact")continue;t.push({id:`${g.id}:${i}`,messageId:g.id,name:n.name,toolCallId:n.toolCallId??null,createdAt:g.createdAt,data:n.data}),i+=1}}return t},tDA=(A)=>{let t=A.lastIndexOf(":");if(t<=0||t===A.length-1)return null;let g=A.slice(0,t),i=A.slice(t+1);if(!/^\d+$/.test(i))return null;return{messageId:g,index:Number.parseInt(i,10)}},gDA=(A,t)=>{return cO(A).find((g)=>g.id===t)},CO=(A)=>typeof A==="object"&&A!==null&&!Array.isArray(A),ADA=(A)=>{let t=A===null||A===void 0?"":typeof A==="object"?JSON.stringify(A):String(A);if(/[",\n\r]/.test(t))return`"${t.replace(/"/g,'""')}"`;return t},_dA=(A)=>{if(Array.isArray(A)&&A.every(CO))return A;if(CO(A))for(let t of["rows","data","items","points"]){let g=A[t];if(Array.isArray(g)&&g.every(CO))return g}return null},nDA=(A)=>{let t=_dA(A);if(!t||t.length===0)return null;let g=[];for(let n of t)for(let Q of Object.keys(n))if(!g.includes(Q))g.push(Q);if(g.length===0)return null;let i=[g.map(ADA).join(",")];for(let n of t)i.push(g.map((Q)=>ADA(n[Q])).join(","));return i.join(`
|
|
8710
8710
|
`)};var mdA=100,iDA=100,xdA=async(A,t,g)=>{let i=[],n;for(let Q=0;Q<iDA;Q++){let o=await A.messages.list(t,{limit:mdA,...n?{cursor:n}:{}}),B=N(o,"Couldn't get artifact (check the thread ID and try again)",g);if(i.push(...B.messages),!B.nextCursor)break;n=B.nextCursor}if(n&&!g)console.error(`Warning: reached the ${iDA}-page limit; the artifact may exist beyond the scanned messages.`);return i},qdA=(A,t,g)=>{if(t)return t;let i=`--thread-id is required to locate artifact '${A}'. Usage: sazabi artifacts get <artifact-id> --thread-id <thread-id>`;if(g)b(i);else r(i);return},ddA=(A,t)=>{if(t.json){Z({id:A.id,messageId:A.messageId,name:A.name,toolCallId:A.toolCallId,createdAt:A.createdAt,data:A.data});return}if(t.format==="csv"){let g=nDA(A.data);if(g===null){r(`Artifact '${A.id}' (${A.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(g);return}console.log(JSON.stringify(A.data,null,2))},QDA=async(A,t)=>{if(!tDA(A)){let h=`Invalid artifact ID: '${A}'. Expected format '<message-id>:<index>' (from 'sazabi artifacts list').`;if(t.json)return b(h);return r(h)}let i=qdA(A,t.threadId,t.json);if(!i)return;let n=P({tokenFlag:t.token,jsonMode:t.json}),Q=z({token:n.token,projectId:n.projectId,apiBaseUrlFlag:t.apiBaseUrl}),o=await xdA(Q,i,t.json),B=gDA(o,A);if(!B){let h=`Artifact '${A}' not found in thread '${i}'. Run 'sazabi artifacts list --thread-id ${i}' to see available artifacts.`;if(t.json)return b(h);return r(h)}ddA(B,t)};nA();aA();IA();var pdA={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"}}},sdA={schema:pdA,columns:["id","name","toolCallId","createdAt"],header:"Artifacts",emptyMessage:"No artifacts found in this thread."},ApA=100,oDA=100,tpA=async(A,t,g)=>{let i=[],n;for(let Q=0;Q<oDA;Q++){let o=await A.messages.list(t,{limit:ApA,...n?{cursor:n}:{}}),B=N(o,"Couldn't list artifacts (check the thread ID and try again)",g);if(i.push(...B.messages),!B.nextCursor)break;n=B.nextCursor}if(n&&!g)console.error(`Warning: reached the ${oDA}-page limit; artifact list may be incomplete for this thread.`);return i},IDA=async(A)=>{let t=P({tokenFlag:A.token,jsonMode:A.json}),g=z({token:t.token,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl}),i=await tpA(g,A.threadId,A.json),Q=cO(i).map((o)=>({id:o.id,name:o.name,toolCallId:o.toolCallId,createdAt:o.createdAt}));j(sdA,Q,{json:A.json})};var BDA=QA("artifacts","Retrieve artifacts produced in a thread").withSubcommands({list:U("list","List artifacts produced in a thread",async(A)=>{let{values:t}=S(A,{token:{type:"string"},"thread-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}}),g=t["thread-id"];if(!g){if(t.json)return b("--thread-id is required. Usage: sazabi artifacts list --thread-id <thread-id>");return r("--thread-id is required. Usage: sazabi artifacts list --thread-id <thread-id>")}await IDA({threadId:g,token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override authentication token"},"thread-id":{type:"string",description:"Thread to list artifacts for (required)"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi artifacts list --thread-id <thread-id> # List artifacts in a thread","sazabi artifacts list --thread-id <thread-id> --json # Output as JSON"]).build(),get:U("get","Get a single artifact's data",async(A)=>{let{values:t,positionals:g}=S(A,{token:{type:"string"},"thread-id":{type:"string"},format:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return b("Artifact ID is required. Usage: sazabi artifacts get <artifact-id> --thread-id <thread-id>");return r("Artifact ID is required. Usage: sazabi artifacts get <artifact-id> --thread-id <thread-id>")}if(g.length>1){let Q=g.slice(1).join(", ");if(t.json)return b(`Unexpected arguments: ${Q}.`);return r(`Unexpected arguments: ${Q}.`)}let n;if(t.format)n=An(t.format,["json","csv"],"Format",t.json);await QDA(i,{token:t.token,threadId:t["thread-id"],format:n,json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<artifact-id>").withOptions({token:{type:"string",description:"Override authentication token"},"thread-id":{type:"string",description:"Thread the artifact belongs to (required)"},format:{type:"string",description:"Output format for non-JSON mode: json (default) or csv"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi artifacts get <artifact-id> --thread-id <thread-id> # Print artifact data","sazabi artifacts get <artifact-id> --thread-id <thread-id> --format csv # Render table/timeseries as CSV","sazabi artifacts get <artifact-id> --thread-id <thread-id> --json # Output as JSON"]).build()}).withExamples(["sazabi artifacts list --thread-id <thread-id> # List artifacts in a thread","sazabi artifacts get <artifact-id> --thread-id <thread-id> # Get one artifact's data"]).build();nA();oO();import{spawn as gpA}from"node:child_process";var f={token:{type:"string"},"api-base-url":{type:"string"},json:{type:"boolean"}},R={token:{type:"string",description:"Override token"},"api-base-url":{type:"string",description:"Override API base URL"},json:{type:"boolean",description:"Output as JSON"}};aA();IA();Ng();var hDA="sazabi:organization:",eDA="sazabi:project:",CDA=(A)=>{let t=null,g=null;for(let i of(A??"").split(/\s+/).filter(Boolean))try{if(i.startsWith(hDA))t=decodeURIComponent(i.slice(hDA.length));else if(i.startsWith(eDA))g=decodeURIComponent(i.slice(eDA.length))}catch{return null}return t?{organizationId:t,projectId:g}:null},_e=(A)=>{if(A==="flag")return"from flag";if(A==="environment")return"from environment";return"from settings"},npA=async(A={})=>{let t=P({jsonMode:A.json}),g=z({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=N(await g.me(),"Couldn't fetch authentication details (run 'sazabi auth login' to sign in again)",A.json);if(A.json){Z({credential:i,activeOrganizationId:t.organizationId,activeProjectId:t.projectId,tokenSource:t.tokenSource,organizationSource:t.organizationSource,projectSource:t.projectSource});return}if(rA("Authentication"),i.credentialType==="user"){LA({Type:`User token (${_e(t.tokenSource)})`,User:i.user.name??i.user.email,Email:i.user.email,"Active organization":t.organizationId&&t.organizationSource?`${t.organizationId} (${_e(t.organizationSource)})`:eg("(none)"),"Active project":t.projectId&&t.projectSource?`${t.projectId} (${_e(t.projectSource)})`:eg("(none)"),Organizations:i.organizations.length.toString(),"Dashboard URL":zi()});return}if(i.credentialType==="secret"){LA({Type:`Secret key (${_e(t.tokenSource)})`,Organization:i.organization.name,"Key name":i.keyName,"Active project":t.projectId&&t.projectSource?`${t.projectId} (${_e(t.projectSource)})`:eg("(none)"),"Dashboard URL":zi()});return}LA({Type:`Partner key (${_e(t.tokenSource)})`,Superorganization:i.superorganization.name,"Dashboard URL":zi()})},ipA=async(A,t={})=>{let g=A.trim();if(!g){if(t.json)return b("Token is required.");return r("Token is required.")}let i=N(mA(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t.json);await yO({token:g,options:t,cliSettings:i,status:"saved"})},cDA=(A)=>{let t=process.platform,g,i;if(t==="darwin")g="open",i=[A];else if(t==="win32")g="cmd",i=["/c","start","",A];else g="xdg-open",i=[A];let n=gpA(g,i,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()},EDA=(A)=>new Promise((t)=>setTimeout(t,A)),QpA=async(A={})=>{let t=N(mA(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",A.json),g=zn(t),i=t.profiles[g]??{},n=DO(i,A.apiBaseUrl),Q=yDA(n,A.authBaseUrl??i.authBaseUrl),o;try{o=await iO({apiBaseUrl:Q})}catch(E){let y=E instanceof Error?E.message:String(E);if(A.json)return b(`Failed to initiate sign-up: ${y}`);return r(`Failed to initiate sign-up: ${y}`)}let B=wDA({profile:i,publicApiBaseUrl:n,authBaseUrl:Q,apiBaseUrlOverride:A.apiBaseUrl,authBaseUrlOverride:A.authBaseUrl,webBaseUrlOverride:A.webBaseUrl,verificationUriComplete:o.verificationUriComplete}),h=`/login/cli?user_code=${encodeURIComponent(o.userCode)}`,e=`${B}/sign-up?returnTo=${encodeURIComponent(h)}`,C=new Date(Date.now()+o.expiresIn*1000),c=o.interval*1000;if(!A.json)bA(),rA("Create a Sazabi account"),bA(),ug(`Opening ${d.info(e)}`),bA(),cDA(e),H("Waiting for sign-up to complete...");while(new Date<C){await EDA(c);try{let E=await QO({apiBaseUrl:Q,deviceCode:o.deviceCode});if(E.status==="pending"){c=(E.interval??o.interval)*1000;continue}if(E.status==="denied"){if(A.json)return b("Sign-up was denied.");return bA(),r("Sign-up was denied.")}if(E.status==="expired"){if(A.json)return b("Sign-up request expired. Try again.");return bA(),r("Sign-up request expired. Try again.")}await yO({token:E.accessToken,options:A,cliSettings:t,status:"authorized",approvedContext:CDA(E.scope)});return}catch(E){let y=E instanceof Error?E.message:String(E);if(A.json)return b(`Sign-up failed: ${y}`);return bA(),r(`Sign-up failed: ${y}`)}}if(A.json)return b("Sign-up request expired. Try again.");return bA(),r("Sign-up request expired. Try again.")},opA=async(A={})=>{await EO(A)},EO=async(A={})=>{let t=N(mA(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",A.json),g=zn(t),i=t.profiles[g]??{},n=DO(i,A.apiBaseUrl),Q=yDA(n,A.authBaseUrl??i.authBaseUrl),o;try{o=await iO({apiBaseUrl:Q})}catch(c){let E=c instanceof Error?c.message:String(c);if(A.json)return b(`Failed to initiate login: ${E}`);return r(`Failed to initiate login: ${E}`)}let B=wDA({profile:i,publicApiBaseUrl:n,authBaseUrl:Q,apiBaseUrlOverride:A.apiBaseUrl,authBaseUrlOverride:A.authBaseUrl,webBaseUrlOverride:A.webBaseUrl,verificationUriComplete:o.verificationUriComplete}),h=ypA(o.verificationUriComplete,B),e=new Date(Date.now()+o.expiresIn*1000),C=o.interval*1000;if(!A.json)bA(),rA("Sign in to Sazabi"),bA(),ug("Enter this code in your browser:"),bA(),ug(d.bold(o.userCode),4),bA(),ug(`Opening ${d.info(h)}`),bA(),cDA(h),H("Waiting for authorization...");while(new Date<e){await EDA(C);try{let c=await QO({apiBaseUrl:Q,deviceCode:o.deviceCode});if(c.status==="pending"){C=(c.interval??o.interval)*1000;continue}if(c.status==="denied"){if(A.json)return b("Authorization was denied.");return bA(),r("Authorization was denied.")}if(c.status==="expired"){if(A.json)return b("Authorization request expired. Try again.");return bA(),r("Authorization request expired. Try again.")}let E=CDA(c.scope);return await yO({token:c.accessToken,options:A,cliSettings:t,status:"authorized",approvedContext:E}),{token:c.accessToken,approvedContext:E}}catch(c){let E=c instanceof Error?c.message:String(c);if(A.json)return b(`Authorization failed: ${E}`);return bA(),r(`Authorization failed: ${E}`)}}if(A.json)return b("Authorization request expired. Try again.");return bA(),r("Authorization request expired. Try again.")},IpA=(A)=>{let t=N(mA(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",A.json),g=N(mt(t),"Couldn't resolve profile (run 'sazabi profiles list' to see available profiles)",A.json),i=Boolean(g.token),n=N(xt(t,{token:void 0,activeOrganizationId:void 0,organizationName:void 0,activeProjectId:void 0,...On(g)}),"Failed to update profile",A.json);if(N(at(n),"Failed to remove credentials",A.json),A.json){Z({removed:i});return}if(i){O("Signed out.");return}H("No credentials were saved.")},yO=async({token:A,options:t,cliSettings:g,status:i,approvedContext:n})=>{let Q=zn(g),o=g.profiles[Q]??{},B=DO(o,t.apiBaseUrl),h=z({token:A,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),e=N(await h.me(),`Couldn't resolve authenticated context at ${B} (pass --api-base-url to target a different environment)`,t.json);if(i==="authorized"&&e.credentialType!=="user"){if(t.json)return b("Expected a user session from device authorization.");return r("Expected a user session from device authorization.")}if(n&&e.credentialType==="user"&&e.activeOrganizationId!==n.organizationId){if(t.json)return b("The issued session did not match the organization approved in the browser.");return r("The issued session did not match the organization approved in the browser.")}let C=g.profiles[Q]?g:{...g,profiles:{...g.profiles,[Q]:{}}},c=C.profiles[Q],E=await BpA({client:h,credential:e,currentProjectId:c.activeProjectId,approvedProjectId:n?n.projectId:void 0,jsonMode:t.json}),y=c.token!==A||c.activeOrganizationId!==E.activeOrganizationId||c.activeProjectId!==E.activeProjectId,w=N(xt(C,{token:A,activeOrganizationId:E.activeOrganizationId,organizationName:E.activeOrganizationName,activeProjectId:E.activeProjectId,apiBaseUrl:t.apiBaseUrl??c.apiBaseUrl,authBaseUrl:t.authBaseUrl??c.authBaseUrl,webBaseUrl:t.webBaseUrl??c.webBaseUrl,...y&&On(c)}),"Failed to update profile",t.json);if(N(at(w),"Failed to save credentials",t.json),t.json){Z({status:i,credential:e,activeOrganizationId:E.activeOrganizationId,activeProjectId:E.activeProjectId,projects:E.projects});return}if(bA(),O(i==="authorized"?"Signed in.":"Token saved."),bA(),epA({credential:e,activeOrganizationName:E.activeOrganizationName,activeProjectId:E.activeProjectId,projects:E.projects}),E.projects.length>0){bA(),rA("Available projects");for(let a of E.projects){let F=a.id===E.activeProjectId?d.success(" (active)"):"";ug(`${a.name} (${a.region})${F}`)}}},BpA=async({client:A,credential:t,currentProjectId:g,approvedProjectId:i,jsonMode:n})=>{if(t.credentialType==="partner")return{projects:[]};let Q=t.credentialType==="user"?t.activeOrganizationId??t.organizations[0]?.id:t.organization.id,o=t.credentialType==="user"?t.organizations.find((h)=>h.id===Q)?.name:t.organization.name,B=Q?N(await A.projects.list({organizationId:Q}),"Couldn't fetch projects (check your organization access and try again)",n).projects:[];return{activeOrganizationId:Q,activeOrganizationName:o,activeProjectId:hpA(B,g,i),projects:B}},hpA=(A,t,g)=>{if(g===null)return;if(g!==void 0)return A.some((i)=>i.id===g)?g:void 0;if(t&&A.some((i)=>i.id===t))return t;return A[0]?.id},epA=({credential:A,activeOrganizationName:t,activeProjectId:g,projects:i})=>{if(A.credentialType==="user"){LA({Type:"User token",User:A.user.name??A.user.email,Organizations:A.organizations.length.toString(),"Active organization":t??"(none)","Active project":i.find((n)=>n.id===g)?.name??"(none)"});return}if(A.credentialType==="secret"){LA({Type:"Secret key",Organization:A.organization.name,"Key name":A.keyName,"Active project":i.find((n)=>n.id===g)?.name??"(none)"});return}LA({Type:"Partner key",Superorganization:A.superorganization.name})},DO=(A,t)=>{return fi({cliFlag:t,globalUrl:A.apiBaseUrl,globalDomain:A.apiDomain,buildUrlFromDomain:(g)=>`https://api.${g}`,defaultUrl:"https://api.sazabi.com"})},yDA=(A,t)=>{if(t)return t;try{let g=new URL(A);if(["localhost","127.0.0.1"].includes(g.hostname)&&["15005","15009"].includes(g.port))return g.port="15001",g.toString().replace(/\/$/,"");if(g.hostname==="api.sazabi.com")return g.hostname="api.platform.sazabi.com",g.toString().replace(/\/$/,"");if(g.hostname==="api.staging.sazabi.dev")return g.hostname="api.platform.staging.sazabi.dev",g.toString().replace(/\/$/,"");return g.toString().replace(/\/$/,"")}catch{return A}},DDA=(A)=>A.replace(/\/+$/,""),yn=(A)=>(A?.trim().length??0)>0,CpA=(A)=>{if(!yn(A))return;try{let t=new URL(A);return`${t.protocol}//${t.host}`}catch{return}},me=(A)=>{if(!yn(A))return;try{let g=new URL(A).hostname.toLowerCase();if(["localhost","127.0.0.1"].includes(g))return"https://localhost:5173";if(["api.staging.sazabi.dev","api.platform.staging.sazabi.dev"].includes(g))return"https://app.staging.sazabi.dev";if(["api.sazabi.com","api.platform.sazabi.com"].includes(g))return"https://app.sazabi.com"}catch{return}return},cpA=(A)=>{if(yn(A.webBaseUrl))return DDA(A.webBaseUrl);if(yn(A.webDomain))return rN(A.webDomain);return},EpA=({profile:A,publicApiBaseUrl:t})=>{if(!(yn(A.authBaseUrl)||yn(A.apiBaseUrl)||yn(A.apiDomain)))return;if(yn(A.authBaseUrl)){let i=me(A.authBaseUrl);if(i)return i}return me(t)},wDA=({profile:A,publicApiBaseUrl:t,authBaseUrl:g,apiBaseUrlOverride:i,authBaseUrlOverride:n,webBaseUrlOverride:Q,verificationUriComplete:o})=>{if(yn(Q))return DDA(Q);let B=process.env.SAZABI_API_URL?.trim(),h=yn(n)||yn(i)||yn(B),e=CpA(o);if(h){let E=yn(n)?me(g):me(t);if(E)return E;if(e)return e}let C=cpA(A);if(C)return C;let c=EpA({profile:A,publicApiBaseUrl:t});if(c)return c;if(e)return e;return"https://app.sazabi.com"},ypA=(A,t)=>{if(!t)return A;try{let g=new URL(A),i=new URL(t);return g.protocol=i.protocol,g.host=i.host,g.toString()}catch{return A}},aDA=QA("auth","Manage authentication credentials").withSubcommands({signup:U("signup","Create a new Sazabi account via browser",async(A)=>{let{values:t,positionals:g}=S(A,{...f,"auth-base-url":{type:"string"},"web-base-url":{type:"string"}},{allowPositionals:!0});if(g.length>0){let i=g.join(", ");if(t.json)return b(`Unexpected arguments: ${i}.`);return r(`Unexpected arguments: ${i}.`)}await QpA({json:t.json,apiBaseUrl:t["api-base-url"],authBaseUrl:t["auth-base-url"],webBaseUrl:t["web-base-url"]})}).withOptions({...R,"auth-base-url":{type:"string",description:"Override auth API base URL"},"web-base-url":{type:"string",description:"Override web app base URL"}}).withExamples(["sazabi auth signup # Create a new account via browser"]).build(),login:U("login","Authenticate via browser",async(A)=>{let{values:t,positionals:g}=S(A,{...f,"auth-base-url":{type:"string"},"web-base-url":{type:"string"}},{allowPositionals:!0});if(g.length>0){let i=g.join(", ");if(t.json)return b(`Unexpected arguments: ${i}.`);return r(`Unexpected arguments: ${i}.`)}await opA({json:t.json,apiBaseUrl:t["api-base-url"],authBaseUrl:t["auth-base-url"],webBaseUrl:t["web-base-url"]})}).withOptions({...R,"auth-base-url":{type:"string",description:"Override auth API base URL"},"web-base-url":{type:"string",description:"Override web app base URL"}}).withExamples(["sazabi auth login # Authenticate via browser"]).build(),save:U("save","Save an existing bearer token",async(A)=>{let{values:t,positionals:g}=S(A,{...f,"web-base-url":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return b("Token is required.");return r("Token is required.")}if(g.length>1){let n=g.slice(1).join(", ");if(t.json)return b(`Unexpected arguments: ${n}.`);return r(`Unexpected arguments: ${n}.`)}await ipA(i,{json:t.json,apiBaseUrl:t["api-base-url"],webBaseUrl:t["web-base-url"]})}).withPositionalArgs("<token>").withOptions({...R,"web-base-url":{type:"string",description:"Override web app base URL"}}).withExamples(["sazabi auth save sazabi_secret_xxx # Save a secret key for future commands"]).build(),logout:U("logout","Remove saved credentials",async(A)=>{let{values:t,positionals:g}=S(A,f,{allowPositionals:!0});if(g.length>0){let i=g.join(", ");if(t.json)return b(`Unexpected arguments: ${i}.`);return r(`Unexpected arguments: ${i}.`)}IpA({json:t.json})}).withOptions(R).withExamples(["sazabi auth logout # Remove saved credentials"]).build(),whoami:U("whoami","Display current authentication context (JSON: top-level activeOrganizationId/activeProjectId are the effective CLI context; credential.* echoes the raw server session)",async(A)=>{let{values:t,positionals:g}=S(A,f,{allowPositionals:!0});if(g.length>0){let i=g.join(", ");if(t.json)return b(`Unexpected arguments: ${i}.`);return r(`Unexpected arguments: ${i}.`)}await npA({json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions(R).withExamples(["sazabi auth whoami # Show current context","sazabi auth whoami --json # Output as JSON"]).build()}).withExamples(["sazabi auth signup # Create a new account via browser","sazabi auth login # Authenticate via browser","sazabi auth save sazabi_secret_xxx # Save an existing token","sazabi auth logout # Remove saved credentials","sazabi auth whoami # Show current context"]).build();nA();aA();IA();var My=(A)=>({id:A.id,name:A.name,status:A.enabled?"active":"paused",source:A.source,kind:A.kind,health:A.health,cronExpression:A.cronExpression,timezone:A.timezone,timeoutSeconds:A.timeoutSeconds,successRate:A.successRate,runCount:A.runCount,failedRunCount:A.failedRunCount,lastRunStatus:A.lastRun?.status??null,lastRunAt:A.lastRun?.startedAt??null,scriptIdentifier:"scriptIdentifier"in A?A.scriptIdentifier:null,scriptId:"scriptId"in A?A.scriptId:null,scriptName:"scriptName"in A?A.scriptName:null,canToggle:"canToggle"in A?A.canToggle:null,createdAt:"createdAt"in A?A.createdAt:null,updatedAt:"updatedAt"in A?A.updatedAt:null}),bDA={id:{label:"ID",type:{kind:"id"}},url:{label:"URL",type:{kind:"nullable-string"}},name:{label:"Name",type:{kind:"string"}},status:{label:"Status",type:{kind:"custom",render:(A)=>A==="active"?"Enabled":"Disabled",serialize:(A)=>A}},source:{label:"Source",type:{kind:"string"}},kind:{label:"Kind",type:{kind:"string"}},health:{label:"Health",type:{kind:"string"}},cronExpression:{label:"Cron",type:{kind:"nullable-string",emptyLabel:"(n/a)"}},timezone:{label:"Timezone",type:{kind:"string"}},timeoutSeconds:{label:"Timeout (s)",type:{kind:"custom",render:(A)=>A==null?"(none)":String(A),serialize:(A)=>A}},successRate:{label:"Success rate",type:{kind:"custom",render:(A)=>A==null?"(n/a)":`${Math.round(Number(A)*100)}%`,serialize:(A)=>A}},runCount:{label:"Runs (7d)",type:{kind:"number"}},failedRunCount:{label:"Failures (7d)",type:{kind:"number"}},lastRunStatus:{label:"Last run status",type:{kind:"nullable-string",emptyLabel:"(never)"}},lastRunAt:{label:"Last run",type:{kind:"nullable-date",emptyLabel:"(never)"}},scriptIdentifier:{label:"Script",type:{kind:"nullable-string"}},scriptId:{label:"Script ID",type:{kind:"nullable-string"}},scriptName:{label:"Script name",type:{kind:"nullable-string"}},canToggle:{label:"Can toggle",type:{kind:"custom",render:(A)=>A==null?"(n/a)":A?"yes":"no",serialize:(A)=>A}},createdAt:{label:"Created at",type:{kind:"nullable-date"}},updatedAt:{label:"Updated at",type:{kind:"nullable-date"}}},DpA={schema:bDA,columns:["name","status","health","cronExpression","lastRunAt"],jsonFields:["id","name","status","source","kind","health","cronExpression","timezone","timeoutSeconds","successRate","runCount","failedRunCount","lastRunStatus","lastRunAt"],header:"Automations",emptyMessage:"No automations found."},uN={layout:"field-list",schema:bDA,fields:["id","url","name","status","source","kind","health","cronExpression","timezone","timeoutSeconds","successRate","runCount","failedRunCount","lastRunStatus","lastRunAt","scriptIdentifier","scriptId","scriptName","canToggle","createdAt","updatedAt"],title:"Automation"},NDA=(A)=>({id:A.id,automationRunKey:A.automationRunKey,status:A.status,scheduledAt:A.scheduledAt,dueAt:A.dueAt,startedAt:A.startedAt,completedAt:A.completedAt,durationMs:A.durationMs,exitCode:A.exitCode,errorMessage:A.errorMessage,automationId:"automationId"in A?A.automationId:null}),uDA={id:{label:"ID",type:{kind:"id"}},automationId:{label:"Automation",type:{kind:"nullable-string"}},automationRunKey:{label:"Run key",type:{kind:"string"}},status:{label:"Status",type:{kind:"string"}},scheduledAt:{label:"Scheduled at",type:{kind:"nullable-date"}},dueAt:{label:"Due at",type:{kind:"nullable-date"}},startedAt:{label:"Started at",type:{kind:"date"}},completedAt:{label:"Completed at",type:{kind:"nullable-date"}},durationMs:{label:"Duration (ms)",type:{kind:"custom",render:(A)=>A==null?"(n/a)":String(A),serialize:(A)=>A}},exitCode:{label:"Exit code",type:{kind:"custom",render:(A)=>A==null?"(n/a)":String(A),serialize:(A)=>A}},errorMessage:{label:"Error",type:{kind:"nullable-string",emptyLabel:"(none)"}}},wpA={schema:uDA,columns:["status","startedAt","durationMs","exitCode"],jsonFields:["id","automationRunKey","status","scheduledAt","dueAt","startedAt","completedAt","durationMs","exitCode","errorMessage"],header:"Automation runs",emptyMessage:"No automation runs found."},apA={layout:"field-list",schema:uDA,fields:["id","automationId","automationRunKey","status","scheduledAt","dueAt","startedAt","completedAt","durationMs","exitCode","errorMessage"],title:"Automation run"},rpA=(A)=>({status:A.status,exitCode:A.exitCode,truncated:A.truncated,durationMs:A.durationMs,startedAt:A.startedAt,completedAt:A.completedAt,stdout:A.stdout,stderr:A.stderr}),bpA={status:{label:"Status",type:{kind:"string"}},exitCode:{label:"Exit code",type:{kind:"custom",render:(A)=>A==null?"(n/a)":String(A),serialize:(A)=>A}},truncated:{label:"Truncated",type:{kind:"custom",render:(A)=>A?"yes":"no",serialize:(A)=>A}},durationMs:{label:"Duration (ms)",type:{kind:"custom",render:(A)=>A==null?"(n/a)":String(A),serialize:(A)=>A}},startedAt:{label:"Started at",type:{kind:"nullable-date"}},completedAt:{label:"Completed at",type:{kind:"nullable-date"}},stdout:{label:"Stdout",type:{kind:"custom",render:(A)=>A?String(A):"(empty)",serialize:(A)=>A}},stderr:{label:"Stderr",type:{kind:"custom",render:(A)=>A?String(A):"(empty)",serialize:(A)=>A}}},NpA={layout:"field-list",schema:bpA,fields:["status","exitCode","truncated","durationMs","startedAt","completedAt","stdout","stderr"],title:"Automation run logs"},Uo=(A)=>{let t=P({tokenFlag:A.token,projectIdFlag:A.projectId,jsonMode:A.json});return{client:z({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),projectId:t.projectId}},UN=(A,t)=>t?{...A,url:xyA(t,A.id)}:A,upA=async(A)=>{let{client:t}=Uo(A),g=N(await t.automations.list({search:A.search,status:A.status,source:A.source,health:A.health,sort:A.sort,limit:A.limit,cursor:A.cursor}),"Couldn't list automations (check the active project and try again)",A.json);j(DpA,g.automations.map(My),{json:A.json,nextCursor:g.nextCursor})},UpA=async(A,t)=>{let{client:g,projectId:i}=Uo(t),n=N(await g.automations.get(A),"Couldn't get automation (run 'sazabi automations list' to see automation IDs)",t.json);X(uN,UN(My(n.automation),i),{json:t.json})},FpA=async(A,t)=>{let g=t.scriptId!==void 0,i=t.script!==void 0,n=t.expressionId!==void 0,Q=Number(g)+Number(i)+Number(n),o=(C)=>{if(t.json){b(C);return}r(C)};if(Q!==1){o("Provide exactly one of --script-id, --script, or --expression-id.");return}if(n){if(t.cronExpression!==void 0||t.timezone!==void 0||t.timeoutSeconds!==void 0){o("Cron and timeout flags are not used with --expression-id log-match automations.");return}if(!t.description?.trim()){o("--description is required for log-match automations (investigation instructions).");return}}let{client:B,projectId:h}=Uo(t),e=N(await B.automations.create({name:A,...t.description!==void 0?{description:t.description}:{},...t.scriptId!==void 0?{scriptId:t.scriptId}:{},...t.script!==void 0?{script:t.script}:{},...t.expressionId!==void 0?{expressionId:t.expressionId}:{},...t.cronExpression!==void 0?{cronExpression:t.cronExpression}:{},...t.timezone!==void 0?{timezone:t.timezone}:{},...t.timeoutSeconds!==void 0?{timeoutSeconds:t.timeoutSeconds}:{},...t.enabled!==void 0?{enabled:t.enabled}:{}}),n?"Couldn't create log-match automation (check the expression ID and description)":"Couldn't create automation (check the script name/ID and try again)",t.json);if(!t.json)O(`Automation "${e.automation.name}" created.`);X(uN,UN(My(e.automation),h),{json:t.json})},LpA=async(A,t)=>{if(t.name===void 0&&t.description===void 0&&t.clearDescription!==!0&&t.cronExpression===void 0&&t.timezone===void 0&&t.timeoutSeconds===void 0){if(t.json){b("Nothing to update. Provide --name, --description, --clear-description, --cron-expression, --timezone, or --timeout-seconds.");return}r("Nothing to update. Provide --name, --description, --clear-description, --cron-expression, --timezone, or --timeout-seconds.");return}if(t.description!==void 0&&t.clearDescription===!0){if(t.json){b("Use either --description or --clear-description, not both.");return}r("Use either --description or --clear-description, not both.");return}let{client:g,projectId:i}=Uo(t),n=N(await g.automations.update({automationId:A,...t.name!==void 0?{name:t.name}:{},...t.clearDescription?{description:null}:t.description!==void 0?{description:t.description}:{},...t.cronExpression!==void 0?{cronExpression:t.cronExpression}:{},...t.timezone!==void 0?{timezone:t.timezone}:{},...t.timeoutSeconds!==void 0?{timeoutSeconds:t.timeoutSeconds}:{}}),"Couldn't update automation (run 'sazabi automations list' to see automation IDs)",t.json);if(!t.json)O(`Automation "${n.automation.name}" updated.`);X(uN,UN(My(n.automation),i),{json:t.json})},UDA=async(A,t,g)=>{let{client:i,projectId:n}=Uo(g),Q=N(t?await i.automations.enable(A):await i.automations.disable(A),t?"Failed to enable automation":"Failed to disable automation",g.json),o=UN(My(Q.automation),n);if(!g.json)O(`Automation "${o.name}" is now ${t?"enabled":"disabled"}.`);X(uN,o,{json:g.json})},SpA=async(A,t)=>UDA(A,!0,t),lpA=async(A,t)=>UDA(A,!1,t),MpA=async(A,t)=>{let{client:g}=Uo(t),i=N(await g.automations.runs.list(A,{status:t.status,limit:t.limit,cursor:t.cursor}),"Couldn't list automation runs (run 'sazabi automations list' to see automation IDs)",t.json);j(wpA,i.runs.map(NDA),{json:t.json,nextCursor:i.nextCursor})},YpA=async(A,t,g)=>{let{client:i}=Uo(g),n=N(await i.automations.runs.get(A,t),"Couldn't get automation run (run 'sazabi automations runs list <automation-id>' to see run IDs)",g.json);X(apA,NDA(n.run),{json:g.json})},$pA=async(A,t,g)=>{let{client:i}=Uo(g),n=N(await i.automations.runs.logs(A,t),"Couldn't get automation run logs (run 'sazabi automations runs list <automation-id>' to see run IDs)",g.json);X(NpA,rpA(n.logs),{json:g.json})},EQ={...f,"project-id":{type:"string"}},yQ={...R,"project-id":{type:"string",description:"Override active project ID"}},kpA=(A,t)=>{let g=A[0];if(!g){if(t){b("Automation name is required.");return}r("Automation name is required.");return}return g},KI=(A,t)=>{let g=A[0];if(!g){if(t){b("Automation ID is required.");return}r("Automation ID is required.");return}return g},rDA=(A,t)=>{let g=A[1];if(!g){if(t){b("Run ID is required.");return}r("Run ID is required.");return}return g},FDA=QA("automations","Manage scheduled automations").withSubcommands({list:U("list","List automations in the active project",async(A)=>{let{values:t}=S(A,{...EQ,search:{type:"string"},status:{type:"string"},source:{type:"string"},health:{type:"string"},sort:{type:"string"},limit:{type:"string"},cursor:{type:"string"}}),g=(C)=>{if(t.json){b(C);return}r(C)},i=t.status;if(i!==void 0&&i!=="active"&&i!=="paused")return g(`Invalid --status value "${i}". Expected "active" or "paused".`);let n=t.source;if(n!==void 0&&n!=="sazabi_managed"&&n!=="custom")return g(`Invalid --source value "${n}". Expected "sazabi_managed" or "custom".`);let Q=t.health,o=["healthy","failing","never_run"];if(Q!==void 0&&!o.includes(Q))return g(`Invalid --health value "${Q}". Expected one of: ${o.join(", ")}.`);let B=t.sort,h=["name","last_run","failures","runs"];if(B!==void 0&&!h.includes(B))return g(`Invalid --sort value "${B}". Expected one of: ${h.join(", ")}.`);let e;if(t.limit!==void 0){if(e=Number(t.limit),!Number.isInteger(e)||e<1||e>100)return g(`Invalid --limit value "${t.limit}". Expected an integer between 1 and 100.`)}await upA({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],search:t.search,status:i,source:n,health:Q,sort:B,limit:e,cursor:t.cursor})}).withOptions({...yQ,search:{type:"string",description:"Filter by automation name (case-insensitive)"},status:{type:"string",description:"Filter by status: active or paused"},source:{type:"string",description:"Filter by source: sazabi_managed or custom"},health:{type:"string",description:"Filter by health: healthy, failing, or never_run"},sort:{type:"string",description:"Sort by: name, last_run, failures, or runs"},limit:{type:"string",description:"Maximum number of automations to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from previous response"}}).withExamples(["sazabi automations list # List all automations","sazabi automations list --status paused # List paused automations"]).build(),get:U("get","Get one automation by ID",async(A)=>{let{values:t,positionals:g}=S(A,EQ,{allowPositionals:!0}),i=KI(g,t.json);if(!i)return;await UpA(i,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<automation-id>").withOptions(yQ).withExamples(["sazabi automations get <automation-id> # Get one automation"]).build(),create:U("create","Create an automation",async(A)=>{let{values:t,positionals:g}=S(A,{...EQ,description:{type:"string"},"script-id":{type:"string"},script:{type:"string"},"expression-id":{type:"string"},"cron-expression":{type:"string"},timezone:{type:"string"},"timeout-seconds":{type:"string"},enabled:{type:"boolean"}},{allowPositionals:!0}),i=kpA(g,t.json);if(!i)return;let n=(o)=>{if(t.json){b(o);return}r(o)},Q;if(t["timeout-seconds"]!==void 0){if(Q=Number(t["timeout-seconds"]),!Number.isInteger(Q)||Q<1||Q>3600)return n(`Invalid --timeout-seconds value "${t["timeout-seconds"]}". Expected an integer between 1 and 3600.`)}await FpA(i,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],description:t.description,scriptId:t["script-id"],script:t.script,expressionId:t["expression-id"],cronExpression:t["cron-expression"],timezone:t.timezone,timeoutSeconds:Q,enabled:t.enabled})}).withPositionalArgs("<name>").withOptions({...yQ,description:{type:"string",description:"Human-readable description (required for log-match automations)"},"script-id":{type:"string",description:"Project script ID to run (cron automations)"},script:{type:"string",description:"Project script name to run (cron automations)"},"expression-id":{type:"string",description:"Log-match expression ID to bind (creates a log-match investigation automation)"},"cron-expression":{type:"string",description:"Cron schedule expression"},timezone:{type:"string",description:"IANA timezone for the schedule"},"timeout-seconds":{type:"string",description:"Run timeout in seconds (1-3600)"},enabled:{type:"boolean",description:"Create the automation enabled"}}).withExamples(["sazabi automations create deploy-nightly --script health --cron-expression '0 3 * * *' # Create from a DB-backed script by name","sazabi automations create deploy-nightly --script-id <script-id> # Create by script ID",'sazabi automations create "Investigate Plain tickets" --expression-id <uuid> --description "When a new Plain ticket is created, investigate …" # Create a log-match investigation automation']).build(),update:U("update","Update an automation",async(A)=>{let{values:t,positionals:g}=S(A,{...EQ,name:{type:"string"},description:{type:"string"},"clear-description":{type:"boolean"},"cron-expression":{type:"string"},timezone:{type:"string"},"timeout-seconds":{type:"string"}},{allowPositionals:!0}),i=KI(g,t.json);if(!i)return;let n=(o)=>{if(t.json){b(o);return}r(o)},Q;if(t["timeout-seconds"]!==void 0){if(Q=Number(t["timeout-seconds"]),!Number.isInteger(Q)||Q<1||Q>3600)return n(`Invalid --timeout-seconds value "${t["timeout-seconds"]}". Expected an integer between 1 and 3600.`)}await LpA(i,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],name:t.name,description:t.description,clearDescription:t["clear-description"],cronExpression:t["cron-expression"],timezone:t.timezone,timeoutSeconds:Q})}).withPositionalArgs("<automation-id>").withOptions({...yQ,name:{type:"string",description:"New automation name"},description:{type:"string",description:"New human-readable description"},"clear-description":{type:"boolean",description:"Clear the automation description"},"cron-expression":{type:"string",description:"New cron schedule expression"},timezone:{type:"string",description:"New IANA timezone for the schedule"},"timeout-seconds":{type:"string",description:"New run timeout in seconds (1-3600)"}}).withExamples(["sazabi automations update <automation-id> --cron-expression '0 4 * * *' # Change the schedule"]).build(),enable:U("enable","Enable an automation",async(A)=>{let{values:t,positionals:g}=S(A,EQ,{allowPositionals:!0}),i=KI(g,t.json);if(!i)return;await SpA(i,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<automation-id>").withOptions(yQ).withExamples(["sazabi automations enable <automation-id> # Enable an automation"]).build(),disable:U("disable","Disable an automation",async(A)=>{let{values:t,positionals:g}=S(A,EQ,{allowPositionals:!0}),i=KI(g,t.json);if(!i)return;await lpA(i,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<automation-id>").withOptions(yQ).withExamples(["sazabi automations disable <automation-id> # Disable an automation"]).build(),runs:U("runs","Inspect automation runs").withSubcommands({list:U("list","List runs for an automation",async(A)=>{let{values:t,positionals:g}=S(A,{...EQ,status:{type:"string"},limit:{type:"string"},cursor:{type:"string"}},{allowPositionals:!0}),i=KI(g,t.json);if(!i)return;let n=(h)=>{if(t.json){b(h);return}r(h)},Q=t.status,o=["running","succeeded","failed","timed_out","cancelled"];if(Q!==void 0&&!o.includes(Q))return n(`Invalid --status value "${Q}". Expected one of: ${o.join(", ")}.`);let B;if(t.limit!==void 0){if(B=Number(t.limit),!Number.isInteger(B)||B<1||B>100)return n(`Invalid --limit value "${t.limit}". Expected an integer between 1 and 100.`)}await MpA(i,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],status:Q,limit:B,cursor:t.cursor})}).withPositionalArgs("<automation-id>").withOptions({...yQ,status:{type:"string",description:"Filter by run status: running, succeeded, failed, timed_out, or cancelled"},limit:{type:"string",description:"Maximum number of runs to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from previous response"}}).withExamples(["sazabi automations runs list <automation-id> # List runs for an automation","sazabi automations runs list <automation-id> --status failed # List failed runs"]).build(),get:U("get","Get one automation run by ID",async(A)=>{let{values:t,positionals:g}=S(A,EQ,{allowPositionals:!0}),i=KI(g,t.json);if(!i)return;let n=rDA(g,t.json);if(!n)return;await YpA(i,n,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<automation-id> <run-id>").withOptions(yQ).withExamples(["sazabi automations runs get <automation-id> <run-id> # Get one automation run"]).build(),logs:U("logs","Get the captured logs for an automation run",async(A)=>{let{values:t,positionals:g}=S(A,EQ,{allowPositionals:!0}),i=KI(g,t.json);if(!i)return;let n=rDA(g,t.json);if(!n)return;await $pA(i,n,{token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withPositionalArgs("<automation-id> <run-id>").withOptions(yQ).withExamples(["sazabi automations runs logs <automation-id> <run-id> # Get captured logs for a run"]).build()}).withExamples(["sazabi automations runs list <automation-id> # List runs for an automation","sazabi automations runs get <automation-id> <run-id> # Get one run","sazabi automations runs logs <automation-id> <run-id> # Get captured logs for a run"]).build()}).withExamples(["sazabi automations list # List all automations","sazabi automations get <automation-id> # Get one automation","sazabi automations create deploy-nightly --script health --cron-expression '0 3 * * *' # Create from a DB-backed script by name","sazabi automations update <automation-id> --cron-expression '0 4 * * *' # Change the schedule","sazabi automations enable <automation-id> # Enable an automation","sazabi automations disable <automation-id> # Disable an automation","sazabi automations runs list <automation-id> # List runs for an automation","sazabi automations runs get <automation-id> <run-id> # Get one run","sazabi automations runs logs <automation-id> <run-id> # Get captured logs for a run"]).build();nA();aA();import{spawn as GpA}from"node:child_process";var DQ=(A)=>{let t=process.platform,g,i;if(t==="darwin")g="open",i=[A];else if(t==="win32")g="cmd",i=["/c","start","",A];else g="xdg-open",i=[A];let n=GpA(g,i,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()},Oi=(A)=>new Promise((t)=>setTimeout(t,A));import{randomUUID as JpA}from"node:crypto";import FN from"node:fs";import TpA from"node:os";import LDA from"node:path";var SDA=()=>LDA.join(TpA.homedir(),".sazabi","pending-purchases"),RpA=()=>{FN.mkdirSync(SDA(),{recursive:!0,mode:448})},lDA=(A)=>LDA.join(SDA(),`${encodeURIComponent(A)}.json`),PpA=(A)=>{for(let t=0;t<50;t+=1){let g;try{g=FN.readFileSync(A,"utf-8")}catch(n){if(n.code==="ENOENT")return null;throw n}if(g.trim().length>0)try{let n=JSON.parse(g);if(n?.idempotencyKey&&n.organizationId&&n.amount)return n}catch{}let i=Date.now()+2;while(Date.now()<i);}return null},MDA=({organizationId:A,amount:t,explicitIdempotencyKey:g})=>{RpA();let i=lDA(A);for(let n=0;n<100;n+=1){let Q={idempotencyKey:g??JpA(),organizationId:A,amount:t,createdAt:new Date().toISOString()};try{return FN.writeFileSync(i,JSON.stringify(Q,null,2),{encoding:"utf-8",mode:384,flag:"wx"}),{kind:"reserved",entry:Q}}catch(B){if(B.code!=="EEXIST")throw B}let o=PpA(i);if(!o)continue;if(o.amount!==t)return{kind:"conflict",existing:o,reason:`A pending purchase for ${o.amount} is unresolved. Resolve it before purchasing a different amount.`};if(g&&g!==o.idempotencyKey)return{kind:"conflict",existing:o,reason:"A pending purchase with a different idempotency key is unresolved. Resolve it first."};return{kind:"resumed",entry:o}}throw Error("Could not reserve a pending purchase after repeated attempts.")},wO=(A)=>{try{FN.unlinkSync(lDA(A))}catch(t){if(t.code!=="ENOENT")throw t}};import{createInterface as RDA}from"node:readline";nA();import{createInterface as fpA}from"node:readline";var zpA="\x03",OpA="\x1B[A",vpA="\x1B[B",ZpA="\x1B[2K",WpA=(A)=>A>0?`\x1B[${A}A`:"",YDA=(A)=>{try{A.setRawMode?.(!1)}catch{}A.pause?.()},$DA=(A,t)=>{return YDA(A),t.write(`
|
|
8711
8711
|
`),process.exit(130)},kDA=(A)=>{if(!A.isTTY||typeof A.setRawMode!=="function")return!1;try{A.setRawMode(!0)}catch{return!1}return A.setEncoding?.("utf8"),A.resume?.(),!0},VpA=(A)=>{let{choice:t,active:g,checked:i}=A,n=i===void 0?"":i?d.success("[x] "):"[ ] ",Q=t.hint?` ${d.muted(`(${t.hint})`)}`:"",o=g?d.info(t.label):t.label;return`${g?d.info("> "):" "}${n}${o}${Q}`},GDA=(A)=>{let{message:t,choices:g,input:i,output:n,multi:Q}=A,o=Math.max(0,g.findIndex((e)=>e.preselected)),B=new Set(Q?g.flatMap((e,C)=>e.preselected?[C]:[]):[]),h=(e)=>{if(e)n.write(WpA(g.length));else n.write(`${d.bold(t)}
|
|
8712
8712
|
`);for(let[C,c]of g.entries())n.write(ZpA),n.write(`${VpA({choice:c,active:C===o,checked:Q?B.has(C):void 0})}
|
|
@@ -8765,7 +8765,7 @@ ${lAt(g)}`:"";if(!A){let Q=`--credentials is required for ${t} (JSON object).${n
|
|
|
8765
8765
|
`)?n.result:`${n.result}
|
|
8766
8766
|
`)};nA();aA();IA();nA();var ogt=/^(\d+)(s|m|h|d)$/u,Igt=(A,t)=>{let g=ogt.exec(A.trim());if(!g){if(t)return b("Duration must use s, m, h, or d units, for example 30m.");return r("Duration must use s, m, h, or d units, for example 30m.")}let i=Number(g[1]),n=g[2];return i*(n==="s"?1000:n==="m"?60000:n==="h"?3600000:86400000)},zwA=(A,t,g)=>{let i=new Date(A);if(Number.isNaN(i.getTime())){let n=`${t} must be a valid ISO-8601 timestamp.`;if(g)return b(n);return r(n)}return i.toISOString()},pe=(A)=>{if(A.last&&(A.from||A.to)){if(A.json)return b("Use either --last or --from/--to, not both.");return r("Use either --last or --from/--to, not both.")}if(A.last){let i=new Date,n=new Date(i.getTime()-Igt(A.last,A.json));if(!Number.isFinite(n.getTime())||!Number.isFinite(i.getTime())){if(A.json)return b("--last is out of the supported date range.");return r("--last is out of the supported date range.")}return{startDate:n.toISOString(),endDate:i.toISOString()}}let t=A.from?zwA(A.from,"--from",A.json):void 0,g=A.to?zwA(A.to,"--to",A.json):void 0;if(t&&g&&new Date(t)>=new Date(g)){if(A.json)return b("--from must be before --to.");return r("--from must be before --to.")}return{startDate:t,endDate:g}};var Bgt={patterns:{label:"Patterns",type:{kind:"custom",render:(A)=>`${Array.isArray(A)?A.length:0} patterns`,serialize:(A)=>A}},meta:{label:"Meta",type:{kind:"custom",render:(A)=>JSON.stringify(A),serialize:(A)=>A}}},hgt={layout:"field-list",schema:Bgt,fields:["patterns","meta"]},egt={serviceName:{label:"Service",type:{kind:"nullable-string",emptyLabel:"(unknown)"}},severity:{label:"Severity",type:{kind:"custom",render:(A)=>typeof A==="string"&&A.length>0?Vi(A):"(none)",serialize:(A)=>A}},occurrences:{label:"Occurrences",type:{kind:"number"},align:"right"},lastSeen:{label:"Last Seen",type:{kind:"nullable-date",emptyLabel:"(never)"}},pattern:{label:"Pattern",type:{kind:"truncated",maxLength:140}},representativeId:{label:"Representative",type:{kind:"nullable-string",emptyLabel:"(none)"}}},Cgt={schema:egt,columns:["serviceName","severity","occurrences","lastSeen","pattern","representativeId"],header:{title:"Log patterns",variant:"search"},emptyMessage:"No matching log patterns."},cgt=(A)=>{let t=pe(A);return{...A.query?{query:A.query}:{},...A.severity?{severity:A.severity}:{},...t.startDate?{startDate:t.startDate}:{},...t.endDate?{endDate:t.endDate}:{},limit:A.limit??25}},OwA=async(A)=>{let t=P({tokenFlag:A.token,projectIdFlag:A.project,jsonMode:A.json}),g=z({token:t.token,projectId:t.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:A.json}),i=N(await g.logs.patterns(cgt(A)),"Failed to query log patterns",A.json);if(A.json){X(hgt,i,{json:!0});return}Egt(i)},Egt=(A)=>{if(A.patterns.length>0)H(`Returned ${A.meta.count} pattern${A.meta.count===1?"":"s"} in ${A.meta.took}ms`);j(Cgt,A.patterns,{count:A.meta.count})};nA();aA();IA();IA();var PN=(A)=>{let t={};for(let g of A??[]){let i=g.indexOf("=");if(i<=0)return wt(`Invalid attribute filter "${g}". Use key=value.`);let n=g.slice(0,i).trim();if(!n)return wt(`Invalid attribute filter "${g}". Attribute key is required.`);t[n]=g.slice(i+1)}return ut(t)};var fN=500,vwA=new Set(["eq","neq","in","contains","starts_with","gt","gte","lt","lte","between","exists"]),ygt=(A)=>{if(A==="@timestamp")return"timestamp";return A},zN=(A,t)=>{for(let g of t){let i=A[g];if(i===void 0||i===null)continue;if(typeof i==="string")return i;if(typeof i==="number"||typeof i==="boolean")return String(i)}return""},Dgt=(A)=>{let t=zN(A,["@timestamp","timestamp","time","ts","date"]);if(!t)return eg("(no time)");return UQ(t)},wgt=(A)=>{return zN(A,["body","message","log","text","content","msg"])||eg("(no message)")},agt=(A)=>{return zN(A,["severity","level","log_level","priority"])},rgt=(A)=>{return zN(A,["service","service_name","serviceName","source"])},bgt=(A,t)=>{let g={};if(!t.omitSearch)g.search={query:A,mode:t.mode??"all",...t.searchFields?.length?{fields:t.searchFields}:{}};if(t.cursor!==void 0||t.limit!==void 0||t.all)g.pagination={limit:t.limit??(t.all?100:50),...t.cursor!==void 0?{cursor:t.cursor}:{}};if(t["sort-field"])g.sort={field:ygt(t["sort-field"]),direction:t["sort-direction"]??"desc"};if(t.select){let n=t.select.split(",").map((Q)=>Q.trim()).filter((Q)=>Q.length>0);if(n.length>0)g.select=n}let i=Fgt(t);if(!i.ok)return{ok:!1,errors:i.errors};if(i.filters.length>0)g.filters=i.filters;return{ok:!0,input:g}};var Ngt=(A)=>{if(A==="true")return!0;if(A==="false")return!1;let t=Number(A);if(A.trim()!==""&&Number.isFinite(t))return t;return A},ugt=(A)=>{let t=Number(A);if(A.trim()!==""&&Number.isFinite(t))return t;return A},Ugt=(A)=>{let t=A.indexOf("=");if(t<=0)return{ok:!1,error:"Filter must use <field>.<op>=<value>."};let g=A.slice(0,t),i=A.slice(t+1),n=g.lastIndexOf(".");if(n<=0||n===g.length-1)return{ok:!1,error:"Filter must use <field>.<op>=<value>."};let Q=g.slice(0,n),o=g.slice(n+1);if(!vwA.has(o))return{ok:!1,error:`Unsupported filter operator: ${o}. Valid operators: ${[...vwA].join(", ")}.`};if(o==="in"){let B=i.split(",").map((h)=>ugt(h.trim())).filter((h)=>h!=="");if(B.length===0)return{ok:!1,error:"in filters must include at least one value."};return{ok:!0,filter:{field:Q,op:o,value:B}}}if(o==="between"){let B=i.includes("..")?i.split(".."):i.split(",");if(B.length!==2)return{ok:!1,error:"between filters must use <from>..<to>."};let[h,e]=B.map((C)=>C.trim());if(!h||!e)return{ok:!1,error:"between filters must use <from>..<to>."};return{ok:!0,filter:{field:Q,op:o,value:{from:h,to:e}}}}if(o==="exists"){if(i!=="true"&&i!=="false")return{ok:!1,error:"exists filters must use true or false."};return{ok:!0,filter:{field:Q,op:o,value:i==="true"}}}return{ok:!0,filter:{field:Q,op:o,value:Ngt(i)}}},Fgt=(A)=>{let t=[],g=[],i=pe({from:A.from,to:A.to,last:A.last,json:A.json});if(i.startDate&&i.endDate)t.push({field:"timestamp",op:"between",value:{from:i.startDate,to:i.endDate}});else if(i.startDate)t.push({field:"timestamp",op:"gte",value:i.startDate});else if(i.endDate)t.push({field:"timestamp",op:"lte",value:i.endDate});if(A.service)t.push({field:"service",op:"eq",value:A.service});if(A.severity)t.push({field:"severity",op:"eq",value:A.severity});if(A.env)t.push({field:"environment",op:"eq",value:A.env});if(A.traceId)t.push({field:"trace_id",op:"eq",value:A.traceId});let n=PN(A.attributes);if(n.success)for(let[Q,o]of Object.entries(n.value))t.push({field:`attributes[${Q}]`,op:"eq",value:o});else g.push(n.error);for(let Q of A.filters??[]){let o=Ugt(Q);if(o.ok)t.push(o.filter);else g.push(`${Q}: ${o.error}`)}if(g.length>0)return{ok:!1,errors:g};return{ok:!0,filters:t}},ZwA=async(A,t)=>{let g=P({tokenFlag:t.token,projectIdFlag:t.project,jsonMode:t.json}),i=z({token:g.token,projectId:g.projectId,apiBaseUrlFlag:t["api-base-url"],jsonMode:t.json}),n=bgt(A,t);if(!n.ok){if(t.json)return b({success:!1,error:"Invalid log query filters",errors:n.errors});return r(`Invalid log query filters: ${n.errors.join("; ")}`)}let Q=n.input,o=t.all?await Lgt(i,Q,t):N(await i.logs.query(Q),"Couldn't query logs (adjust the filters or time window and try again)",t.json);if(t.json){Z(o);return}Sgt(o)},Lgt=async(A,t,g)=>{let i=[],n=t.pagination?.cursor,Q=0;do{let o={...t,pagination:{limit:t.pagination?.limit??g.limit??100,...n?{cursor:n}:{}}},B=N(await A.logs.query(o),"Failed to query logs",g.json);i.push(...B.data),Q+=B.meta.took,n=B.nextCursor}while(n);return{data:i,nextCursor:null,meta:{count:i.length,took:Q}}},Sgt=(A)=>{let{data:t,nextCursor:g,meta:i}=A;if(t.length===0){Xi("No matching log rows. Widen the time window with --last or loosen filters.");return}H(`Returned ${i.count} row${i.count===1?"":"s"} in ${i.took}ms`);let n=t.map((Q)=>{let o=Q,B=agt(o);return{time:Dgt(o),severity:B?Vi(B,B):d.muted(eg("(sev)")),service:rgt(o)||eg("(service)"),message:Pg(wgt(o),200)}});hi(n,[{header:"Time (UTC)",key:"time"},{header:"Severity",key:"severity"},{header:"Service",key:"service"},{header:"Message",key:"message"}],{header:{title:"Log query results",variant:"search",count:i.count}}),Hi({type:"cursor",nextCursor:g})};nA();aA();IA();var lgt={backend:{label:"Backend",type:{kind:"custom",render:(A)=>{let t=A;return`${t.name} (${t.id})`},serialize:(A)=>A}},features:{label:"Features",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"(none)",serialize:(A)=>A}},commands:{label:"Commands",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"(none)",serialize:(A)=>A}},question:{label:"Question",type:{kind:"custom",render:(A)=>String(A??""),serialize:(A)=>A}},indexStatus:{label:"Index",type:{kind:"custom",render:(A)=>String(A??"unknown"),serialize:(A)=>A}},selectedAttributeKeys:{label:"Selected Attributes",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"(none)",serialize:(A)=>A}},selectedBundles:{label:"Selected Bundles",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.map((t)=>{let g=t;return`${g.service} (${g.keys.length} keys)`}).join("; "):"(none)",serialize:(A)=>A}},queryableFields:{label:"Queryable",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"(none)",serialize:(A)=>A}},searchableFields:{label:"Searchable",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"(none)",serialize:(A)=>A}},observedServiceNames:{label:"Observed Services",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"(none)",serialize:(A)=>A}},observedAttributeKeys:{label:"Observed Attributes",type:{kind:"custom",render:(A)=>Array.isArray(A)?A.join(", "):"(none)",serialize:(A)=>A}},schemaContext:{label:"Schema Context",type:{kind:"custom",render:(A)=>A?JSON.stringify(A):"(none)",serialize:(A)=>A}}},Mgt={layout:"field-list",schema:lgt,fields:["backend","features","commands","question","indexStatus","selectedAttributeKeys","selectedBundles","queryableFields","searchableFields","observedServiceNames","observedAttributeKeys","schemaContext"]},WwA=async(A)=>{let t=P({tokenFlag:A.token,projectIdFlag:A.project,jsonMode:A.json}),g=z({token:t.token,projectId:t.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:A.json}),i=N(await g.logs.schema({...A.question?{question:A.question}:{},...A["top-k"]!==void 0?{topK:A["top-k"]}:{}}),"Couldn't fetch log schema (check the active project and try again)",A.json);if(A.json){X(Mgt,i,{json:!0});return}Ygt(i)},Ygt=(A)=>{if(rA("Log backend"),LA({Backend:`${A.backend.name} (${A.backend.id})`,Kind:A.backend.kind,Commands:A.commands.join(", "),Features:A.features.join(", ")||"(none)",Question:A.question??"(none)",Index:A.indexStatus}),rA("Selected schema"),LA({Attributes:A.selectedAttributeKeys.join(", ")||"(none)",Bundles:String(A.selectedBundles.length)}),A.selectedBundles.length>0)hi(A.selectedBundles.map((t)=>({service:Pg(t.service,40),keys:Pg(t.keys.join(", "),80),rows:String(t.rowCount)})),[{header:"Service",key:"service"},{header:"Keys",key:"keys"},{header:"Rows",key:"rows"}]);if(rA("Normalized fields"),LA({Queryable:A.queryableFields.join(", ")||"(none)",Searchable:A.searchableFields.join(", ")||"(none)"}),A.observedServiceNames.length>0)hi(A.observedServiceNames.map((t)=>({service:Pg(t,80)})),[{header:"Observed Services",key:"service"}])};nA();Sy();aA();IA();Ng();var VwA=["ERROR","WARN","INFO","DEBUG","TRACE"],$gt="3010",kgt=(A)=>{return A.startsWith("[")&&A.endsWith("]")?A.slice(1,-1):A},Ggt=(A)=>{let t=kgt(A);return t==="localhost"||t==="127.0.0.1"||t==="::1"},Jgt=200,Tgt=(A,t)=>{if(!t)return"";let g=t.kind==="all"?Object.keys(A).sort():t.keys,i=[];for(let n of g){let Q=A[n];if(Q===void 0)continue;i.push(d.muted(`${n}=${Pg(Q,Jgt)}`))}return i.length>0?` ${i.join(" ")}`:""},Rgt=({log:A,attrsDisplay:t})=>{let g=UQ(A.timestamp).split("T")[1]??A.timestamp,i=Vi(A.severity,A.severity.padEnd(7)),n=d.cyan(A.service.padEnd(20)),Q=A.body.length>120?`${A.body.substring(0,117)}...`:A.body,o=Tgt(A.attributes,t);return`[${g}] ${i} ${n} ${Q}${o}`},Pgt=(A)=>{if(A===void 0)return;if(A.trim().toLowerCase()==="all")return{kind:"all"};let t=A.split(",").map((g)=>g.trim()).filter((g)=>g.length>0);return t.length>0?{kind:"keys",keys:t}:void 0},ZO=async(A)=>{let t=new AbortController,g,i=0,n,Q,o=()=>{g="interrupted",t.abort()},B=N(await A.client.logs.tail({...A.projectId?{projectId:A.projectId}:{},...A.region?{region:A.region}:{},filters:A.filters??{},signal:t.signal}),"Couldn't tail logs (check your network connection and try again)",A.json);if(A.onConnected?.(),process.on("SIGINT",o),A.durationSeconds&&A.durationSeconds>0)Q=setTimeout(()=>{g="duration",t.abort()},A.durationSeconds*1000);try{for await(let h of B)if(i+=1,A.onEvent(h),A.stopWhen?.(h,i))break}catch(h){if(g==="interrupted"||g==="duration"||h instanceof Error&&h.name==="AbortError")n=void 0;else n=h instanceof Error?h:Error(String(h))}finally{if(process.removeListener("SIGINT",o),Q)clearTimeout(Q);t.abort()}return{logCount:i,closeReason:g,streamError:n}},HwA=async(A)=>{let t=N(oi(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)"),g=A.json??!1,i=Ogt(t,A.apiBaseUrl),n=zgt(A.severities,g),Q=vO(A.services),o=vO(A.environments),B=PN(A.attribute);if(!B.success){if(g)return b(B.error);return r(B.error)}let h=Object.keys(B.value).length>0?B.value:void 0,e=Pgt(A.attrs),C=P({tokenFlag:A.token,jsonMode:g}),c=await Wgt({apiBaseUrlFlag:A.apiBaseUrl,jsonMode:g,projectId:C.projectId,regionFlag:A.region,token:C.token}),E=CQ({token:C.token,projectId:C.projectId,baseUrl:i,tailBaseUrl:Zgt(t,A.tailBaseUrl,c,i)}),y={severities:n,services:Q,environments:o,searchTerm:A.search,traceId:A.traceId,attributes:h};if(!g)fgt({attributes:h,environments:o,region:c,search:A.search,services:Q,severities:n,traceId:A.traceId});let{logCount:w,closeReason:a,streamError:u}=await ZO({client:E,projectId:C.projectId,region:c,filters:y,durationSeconds:A.duration,json:g,onConnected:()=>{if(!g)O("Connected. Waiting for logs..."),H("Press Ctrl+C to stop (auto-reconnects on disconnect)."),bA()},onEvent:(F)=>{if(g){Z(F);return}Ki(Rgt({log:F,attrsDisplay:e}))}});if(u){if(g)return b(u.message);bA(),BC(),Zn(u.message);return}if(g)return;if(bA(),a==="duration")H("Duration reached, closing connection...");if(a==="interrupted")H("Interrupted, closing connection...");BC(),H(`Connection closed. Received ${wn(w,"log")}.`)},fgt=(A)=>{if(rA("Tailing logs"),A.severities?.length)H(`Severities: ${A.severities.join(", ")}`);if(A.services?.length)H(`Services: ${A.services.join(", ")}`);if(A.environments?.length)H(`Environments: ${A.environments.join(", ")}`);if(A.search)H(`Search: ${A.search}`);if(A.traceId)H(`Trace ID: ${A.traceId}`);if(A.attributes&&Object.keys(A.attributes).length>0){let t=Object.entries(A.attributes).map(([g,i])=>`${g}=${i}`).join(", ");H(`Attributes: ${t}`)}if(A.region)H(`Region: ${A.region}`);BC(),bA()},vO=(A)=>{if(!A)return;let t=A.split(",").map((g)=>g.trim()).filter((g)=>g.length>0);return t.length>0?t:void 0},zgt=(A,t)=>{let g=vO(A)?.map((Q)=>Q.toUpperCase());if(!g)return;let i=g.find((Q)=>!VwA.includes(Q));if(!i)return g;let n=`Invalid severity: ${i}. Valid values: ${VwA.join(", ")}.`;if(t)return b(n);return r(n)},Ogt=(A,t)=>{return fi({cliFlag:t,globalUrl:A.apiBaseUrl,globalDomain:A.apiDomain,buildUrlFromDomain:(g)=>`https://api.${g}`,defaultUrl:"https://api.sazabi.com"})},vgt=(A)=>{let t=(()=>{try{return new URL(A)}catch{return null}})();if(!t)return;if(!Ggt(t.hostname))return;return t.protocol="http:",t.port=$gt,t.pathname="/v1/tail",t.search="",t.hash="",t.toString()},Zgt=(A,t,g,i)=>{if(t)return XwA(t);if(A.tailBaseUrl)return XwA(A.tailBaseUrl);let n=vgt(i);if(n)return n;if(A.tailDomain&&g)return`https://${g}.tail.${A.tailDomain}/v1/tail`;if(g){try{let Q=new URL(i).hostname;if(Q.endsWith(".sazabi.dev")){let o=Q.includes(".staging.")?"staging.sazabi.dev":"development.sazabi.dev";return`https://${g}.tail.${o}/v1/tail`}}catch{}return`https://${g}.tail.sazabi.com/v1/tail`}return},XwA=(A)=>{let t=A.replace(/^wss:/i,"https:").replace(/^ws:/i,"http:"),g=(()=>{try{return new URL(t)}catch{return null}})();if(!g)return t;return g.pathname="/v1/tail",g.search="",g.hash="",g.toString()},Wgt=async(A)=>{if(A.regionFlag){if(!/^[a-z]+-[a-z]+-\d+$/.test(A.regionFlag))Zn(`Invalid region format: "${A.regionFlag}". Expected format: us-west-2.`),process.exit(1);return A.regionFlag}if(!A.projectId)return;return(await bN({token:A.token,projectId:A.projectId,apiBaseUrlFlag:A.apiBaseUrlFlag,jsonMode:A.jsonMode})).region};nA();aA();IA();var Vgt={total:{label:"Total",type:{kind:"number"}},startDate:{label:"Start",type:{kind:"date"}},endDate:{label:"End",type:{kind:"date"}},interval:{label:"Interval",type:{kind:"string"}},series:{label:"Series",type:{kind:"custom",render:(A)=>`${Array.isArray(A)?A.length:0} series`,serialize:(A)=>A}}},Xgt={layout:"field-list",schema:Vgt,fields:["total","startDate","endDate","interval","series"]},Hgt={group:{label:"Group",type:{kind:"string"}},total:{label:"Total",type:{kind:"number"},align:"right"},points:{label:"Points",type:{kind:"custom",render:(A)=>Array.isArray(A)?String(A.length):"0",serialize:(A)=>A},align:"right"}},Kgt={schema:Hgt,columns:["group","total","points"],header:{title:"Log volume",variant:"results"},emptyMessage:"No log volume found."},jgt=(A)=>{if(A==="service")return"service_name";if(A==="severity")return"severity_text";return A},_gt=(A)=>{let t=new Date,g=pe(A),i=g.endDate??t.toISOString();return{startDate:g.startDate??new Date(new Date(i).getTime()-3600000).toISOString(),endDate:i,...A.interval?{interval:A.interval}:{},...A.groupBy?{groupBy:jgt(A.groupBy)}:{},filters:{...A.service?{service_name:A.service}:{},...A.severity?{severity_text:A.severity}:{},...A.env?{environment:A.env}:{}}}},KwA=async(A)=>{let t=P({tokenFlag:A.token,projectIdFlag:A.project,jsonMode:A.json}),g=z({token:t.token,projectId:t.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:A.json}),i=N(await g.logs.volume(_gt(A)),"Failed to query log volume",A.json);if(A.json){X(Xgt,i,{json:!0});return}mgt(i)},mgt=(A)=>{if(A.series.length>0)H(`Total ${A.total} logs from ${A.startDate} to ${A.endDate} at ${A.interval}`);j(Kgt,A.series,{count:A.series.length})};var vy=(A,t)=>{let g=[],i=`--${t}=`;for(let n=0;n<A.length;n+=1){let Q=A[n];if(Q===void 0)continue;if(Q===`--${t}`){let o=A[n+1];if(o!==void 0&&!o.startsWith("-"))g.push(o),n+=1;continue}if(Q.startsWith(i))g.push(Q.slice(i.length))}return g},jwA=QA("logs","Stream, search, and forward logs").withSubcommands({schema:U("schema","Describe the active log backend and optionally retrieve schema bundles",async(A)=>{let{values:t}=S(A,{...f,project:{type:"string"},question:{type:"string"},"top-k":{type:"string"}}),g=t["top-k"],i=typeof g==="string"&&g.length>0?Number.parseInt(g,10):void 0;if(i!==void 0&&(!Number.isFinite(i)||i<1))throw Error("--top-k must be a positive integer");let n=typeof t.question==="string"&&t.question.trim().length>0?t.question.trim():void 0,Q={token:t.token,project:t.project,question:n,"top-k":i,json:t.json,"api-base-url":t["api-base-url"]};await WwA(Q)}).withOptions({...R,project:{type:"string",description:"Override project ID (default: active project)"},question:{type:"string",description:"Optional natural-language question for schema-bundle retrieval"},"top-k":{type:"string",description:"Max schema bundles to return when --question is set"}}).withExamples(["sazabi logs schema --json # Backend, fields, and recent key hints",'sazabi logs schema --question "5xx errors by route" # Question-conditioned schema bundles','sazabi logs schema --question "intake batch failures" --json # Machine-readable schema bundles']).build(),tail:U("tail","Stream logs from the active project in real time",async(A)=>{let{values:t}=S(A,{...f,severities:{type:"string"},services:{type:"string"},environments:{type:"string"},search:{type:"string"},"trace-id":{type:"string"},attribute:{type:"string"},attrs:{type:"string"},duration:{type:"string"},"tail-base-url":{type:"string"},region:{type:"string"}}),g={};if(t.token)g.token=t.token;if(t.severities)g.severities=t.severities;if(t.services)g.services=t.services;if(t.environments)g.environments=t.environments;if(t.search)g.search=t.search;if(t["trace-id"])g.traceId=t["trace-id"];let i=vy(A,"attribute");if(i.length>0)g.attribute=i;if(t.attrs)g.attrs=t.attrs;if(t.duration)g.duration=Cg(t.duration,1,Number.MAX_SAFE_INTEGER,"Duration",t.json);if(t.json)g.json=!0;if(t["tail-base-url"])g.tailBaseUrl=t["tail-base-url"];if(t.region)g.region=t.region;if(t["api-base-url"])g.apiBaseUrl=t["api-base-url"];await HwA(g)}).withOptions({...R,severities:{type:"string",description:"Filter by comma-separated severities (e.g., ERROR,WARN,INFO)"},services:{type:"string",description:"Filter by comma-separated service names"},environments:{type:"string",description:"Filter by comma-separated environments"},search:{type:"string",description:"Filter by search term (case-insensitive)"},"trace-id":{type:"string",description:"Filter by trace ID"},attribute:{type:"string",description:"Filter by log attribute as key=value (exact match). Repeat for multiple attributes."},attrs:{type:"string",description:"Show log attributes in output: comma-separated keys, or 'all'"},duration:{type:"string",description:"Duration to tail in seconds (default: unlimited)"},"tail-base-url":{type:"string",description:"Override tail SSE base URL"},region:{type:"string",description:"Override project region"}}).withExamples(["sazabi logs tail # Tail all logs in real time","sazabi logs tail --severities ERROR,WARN # Tail only errors and warnings","sazabi logs tail --services api,worker # Tail specific services","sazabi logs tail --environments production,staging # Tail specific environments",'sazabi logs tail --search "database" # Tail logs matching search term',"sazabi logs tail --attribute user.id=42 # Tail logs with an exact attribute value","sazabi logs tail --attrs model,prompt # Show selected attributes per line","sazabi logs tail --attrs all # Show every attribute per line","sazabi logs tail --json # Output as JSON"]).build(),query:U("query","Search stored logs in the current project (POST /logs/query)",async(A)=>{let{values:t,positionals:g}=S(A,{...f,project:{type:"string"},limit:{type:"string"},cursor:{type:"string"},mode:{type:"string"},"sort-field":{type:"string"},"sort-direction":{type:"string"},select:{type:"string"},from:{type:"string"},to:{type:"string"},last:{type:"string"},service:{type:"string"},severity:{type:"string"},env:{type:"string"},"trace-id":{type:"string"},attribute:{type:"string"},filter:{type:"string"},"search-field":{type:"string"},"query-all":{type:"boolean"},all:{type:"boolean"}},{allowPositionals:!0}),i=g.join(" ").trim(),n=vy(A,"filter"),Q=vy(A,"attribute"),o=vy(A,"search-field"),B=Boolean(t.from||t.to||t.last||t.service||t.severity||t.env||t["trace-id"])||n.length>0||Q.length>0;if(!i&&!t["query-all"]&&!B){if(t.json)return b("Search text, a structured filter, or --query-all is required. Usage: sazabi logs query <search-text> [options]");return r("Search text, a structured filter, or --query-all is required. Usage: sazabi logs query <search-text> [options]")}if(i.length>fN){if(t.json)return b(`Search text must be at most ${fN} characters.`);return r(`Search text must be at most ${fN} characters.`)}if(i&&t["query-all"]){if(t.json)return b("Pass either a search phrase or --query-all, not both.");return r("Pass either a search phrase or --query-all, not both.")}if(t.mode&&!i){if(t.json)return b("--mode requires search text (search is omitted).");return r("--mode requires search text (search is omitted).")}let h={token:t.token,project:t.project,json:t.json,"api-base-url":t["api-base-url"],omitSearch:t["query-all"]===!0||!i,from:t.from,to:t.to,last:t.last,service:t.service,severity:t.severity,env:t.env,traceId:t["trace-id"],attributes:Q,filters:n,searchFields:o,all:t.all};if(t.limit)h.limit=Cg(t.limit,1,1000,"Limit",t.json);if(t.cursor)h.cursor=t.cursor;if(t.mode)h.mode=An(t.mode,["any","all","phrase"],"Mode",t.json);if(t["sort-field"])h["sort-field"]=t["sort-field"];if(t["sort-direction"]&&!t["sort-field"]){if(t.json)return b("--sort-direction requires --sort-field.");return r("--sort-direction requires --sort-field.")}if(t["sort-direction"])h["sort-direction"]=An(t["sort-direction"],["asc","desc"],"Sort direction",t.json);if(t.select)h.select=t.select;await ZwA(i,h)}).withPositionalArgs("[search-text]").withOptions({...R,project:{type:"string",description:"Override project ID (default: active project)"},limit:{type:"string",description:"Max rows to return (1-1000, default: 50)"},cursor:{type:"string",description:"Pagination cursor from a previous response"},mode:{type:"string",description:"Token match mode: any, all, or phrase (default: all)"},"sort-field":{type:"string",description:"Field to sort by (e.g. @timestamp)"},"sort-direction":{type:"string",description:"Sort direction: asc or desc (default: desc)"},select:{type:"string",description:"Comma-separated fields to return"},from:{type:"string",description:"Start time as ISO-8601 timestamp"},to:{type:"string",description:"End time as ISO-8601 timestamp"},last:{type:"string",description:"Relative time window, for example 30m, 6h, or 7d"},service:{type:"string",description:"Filter by service name"},severity:{type:"string",description:"Filter by severity, for example ERROR"},env:{type:"string",description:"Filter by deployment environment"},"trace-id":{type:"string",description:"Filter by trace ID"},attribute:{type:"string",description:"Filter by log attribute as key=value (exact match); repeatable"},filter:{type:"string",description:"Structured filter as <field>.<op>=<value>; repeatable"},"search-field":{type:"string",description:"Restrict full-text search to a field (body, message, attributes, or attributes[<key>]); repeatable"},"query-all":{type:"boolean",description:"Omit full-text search and return the API default slice (sort/pagination only; server may require other filters)"},all:{type:"boolean",description:"Fetch all pages until the server returns no cursor"}}).withExamples(['sazabi logs query "connection refused" --last 1h --service api --severity ERROR # Search recent API errors',"sazabi logs query --trace-id abc123 --select timestamp,service,severity,body # Find logs for one trace","sazabi logs query --filter http_status_code.gte=500 --limit 100 --json # Machine-readable structured filter","sazabi logs query --attribute user.id=42 --last 1h --json # Filter by an exact attribute value",'sazabi logs query "beach house" --search-field attributes --last 1h # Full-text search inside attribute values',"sazabi logs query --query-all --select timestamp,body,attributes --json # Return the full attributes map","sazabi logs query error --mode any --limit 100 # Match any token with a larger page","sazabi logs query --query-all --limit 20 --sort-field @timestamp # Recent rows without full-text search","sazabi logs query slow --json # Machine-readable output"]).build(),patterns:U("patterns","Search normalized log patterns for discovery",async(A)=>{let{values:t,positionals:g}=S(A,{...f,project:{type:"string"},severity:{type:"string"},from:{type:"string"},to:{type:"string"},last:{type:"string"},limit:{type:"string"}},{allowPositionals:!0}),i={token:t.token,project:t.project,query:g.join(" ").trim()||void 0,severity:t.severity,from:t.from,to:t.to,last:t.last,json:t.json,"api-base-url":t["api-base-url"]};if(t.limit)i.limit=Cg(t.limit,1,100,"Limit",t.json);await OwA(i)}).withPositionalArgs("[pattern-text]").withOptions({...R,project:{type:"string",description:"Override project ID (default: active project)"},severity:{type:"string",description:"Filter by severity, for example ERROR"},from:{type:"string",description:"Start time as ISO-8601 timestamp"},to:{type:"string",description:"End time as ISO-8601 timestamp"},last:{type:"string",description:"Relative time window, for example 30m, 6h, or 7d"},limit:{type:"string",description:"Max patterns to return (1-100, default: 25)"}}).withExamples(['sazabi logs patterns "connection refused" --severity ERROR --limit 25 # Find recurring error patterns',"sazabi logs patterns --last 24h --json # Export recent patterns"]).build(),volume:U("volume","Summarize log volume by time and optional dimension",async(A)=>{let{values:t}=S(A,{...f,project:{type:"string"},from:{type:"string"},to:{type:"string"},last:{type:"string"},interval:{type:"string"},"group-by":{type:"string"},service:{type:"string"},severity:{type:"string"},env:{type:"string"}}),g={token:t.token,project:t.project,from:t.from,to:t.to,last:t.last,service:t.service,severity:t.severity,env:t.env,json:t.json,"api-base-url":t["api-base-url"]};if(t.interval)g.interval=An(t.interval,["1m","5m","15m","1h"],"Interval",t.json);if(t["group-by"])g.groupBy=An(t["group-by"],["service","severity","environment"],"Group by",t.json);await KwA(g)}).withOptions({...R,project:{type:"string",description:"Override project ID (default: active project)"},from:{type:"string",description:"Start time as ISO-8601 timestamp"},to:{type:"string",description:"End time as ISO-8601 timestamp"},last:{type:"string",description:"Relative time window, for example 30m, 6h, or 7d"},interval:{type:"string",description:"Bucket interval: 1m, 5m, 15m, or 1h"},"group-by":{type:"string",description:"Group by service, severity, or environment"},service:{type:"string",description:"Filter by service name"},severity:{type:"string",description:"Filter by severity, for example ERROR"},env:{type:"string",description:"Filter by deployment environment"}}).withExamples(["sazabi logs volume --last 6h --group-by service # Compare service log volume","sazabi logs volume --last 24h --severity ERROR --interval 15m --json # Export error volume"]).build(),"native-query":U("native-query","Run a backend-native read-only log query",async(A)=>{let{values:t}=S(A,{...f,project:{type:"string"},query:{type:"string"},file:{type:"string",short:"f"}}),g={token:t.token,project:t.project,query:t.query,file:t.file,json:t.json,"api-base-url":t["api-base-url"]};await fwA(g)}).withOptions({...R,project:{type:"string",description:"Override project ID (default: active project)"},query:{type:"string",description:"Backend-native query text"},file:{type:"string",short:"f",description:"Read backend-native query text from a file"}}).withExamples(['sazabi logs native-query --query "SELECT service_name, count() FROM log_volume_per_minute GROUP BY service_name LIMIT 20" # Run backend-native query text',"sazabi logs native-query --file investigation.sql --json # Run a query from a file"]).build(),forward:U("forward","Forward plaintext logs to the active project",async(A)=>{let{values:t}=S(A,{...f,file:{type:"string",short:"f"},follow:{type:"boolean"},"batch-size":{type:"string"},"intake-base-url":{type:"string"},"public-key":{type:"string"},service:{type:"string"},attribute:{type:"string"},region:{type:"string"}}),g={};if(t.token)g.token=t.token;if(t.file)g.file=t.file;if(t.follow)g.follow=t.follow;if(t["batch-size"])g.batchSize=Cg(t["batch-size"],1,Number.MAX_SAFE_INTEGER,"Batch size",t.json);if(t["api-base-url"])g.apiBaseUrl=t["api-base-url"];if(t["intake-base-url"])g.intakeBaseUrl=t["intake-base-url"];if(t.region)g.region=t.region;if(t["public-key"])g.publicKey=t["public-key"];if(t.service)g.service=t.service;let i=vy(A,"attribute");if(i.length>0)g.attributes=i;await PwA({...g,json:t.json})}).withOptions({...R,json:{type:"boolean",description:"Output a final JSON summary"},file:{type:"string",short:"f",description:"Read from file instead of stdin"},follow:{type:"boolean",description:"Follow file for new lines (like tail -f)"},"batch-size":{type:"string",description:"Number of logs to batch before sending (default: 100)"},"intake-base-url":{type:"string",description:"Override intake base URL"},"public-key":{type:"string",description:"Use this public key value (skip creating/storing)"},service:{type:"string",description:"Set OTLP service.name for forwarded lines (default: sazabi-cli)"},attribute:{type:"string",description:"Attach a log attribute as key=value. Repeat for multiple attributes."},region:{type:"string",description:"Override project region"}}).withExamples(['echo "Log message" | sazabi logs forward # Forward from stdin',"sazabi logs forward --file app.log # Forward from file","sazabi logs forward --file app.log --follow # Forward file with tail -f behavior","sazabi logs forward --file app.log --batch-size 50 # Forward with custom batch size"]).build()}).withExamples(["sazabi logs tail # Tail all logs in real time","sazabi logs tail --severities ERROR,WARN # Tail only errors and warnings",'sazabi logs query "timeout" # Search stored logs',"sazabi logs forward --file app.log # Forward from file"]).build();nA();aA();IA();var _wA={connectionId:{label:"ID",type:{kind:"string"}},connectionKey:{label:"Key",type:{kind:"string"}},url:{label:"URL",type:{kind:"string"}},providerId:{label:"Provider",type:{kind:"string"}},displayName:{label:"Name",type:{kind:"string"}},source:{label:"Source",type:{kind:"string"}},installStatus:{label:"Status",type:{kind:"string"}},authMode:{label:"Auth",type:{kind:"string"}},transport:{label:"Transport",type:{kind:"string"}},serverUrl:{label:"Server URL",type:{kind:"string"}},readOnly:{label:"Read-only",type:{kind:"boolean"}},enabledToolCount:{label:"Enabled tools",type:{kind:"number"}},connectedAt:{label:"Connected",type:{kind:"nullable-date"}},createdAt:{label:"Created",type:{kind:"date"}},updatedAt:{label:"Updated",type:{kind:"date"}}},xgt={schema:_wA,columns:["connectionId","providerId","displayName","installStatus","enabledToolCount","url"],header:"MCP connectors",emptyMessage:"No MCP connectors configured. Add one in Settings > MCP connectors in the dashboard."},ON={layout:"field-list",schema:_wA,fields:["connectionId","connectionKey","providerId","displayName","source","installStatus","authMode","transport","serverUrl","url","readOnly","enabledToolCount","connectedAt","createdAt","updatedAt"],title:"MCP connector"},qgt={name:{label:"Name",type:{kind:"string"}},title:{label:"Title",type:{kind:"string"}},description:{label:"Description",type:{kind:"string"}},isReadOnly:{label:"Read-only",type:{kind:"boolean"}},enabled:{label:"Enabled",type:{kind:"boolean"}}},dgt={schema:qgt,columns:["name","title","isReadOnly","enabled"],header:"Tools",emptyMessage:"No tools discovered for this connector."},pgt={providerId:{label:"Provider",type:{kind:"string"}},label:{label:"Name",type:{kind:"string"}},authMode:{label:"Auth",type:{kind:"string"}},availability:{label:"Availability",type:{kind:"string"}},hasSetupSkill:{label:"Setup skill",type:{kind:"boolean"}}},sgt={schema:pgt,columns:["providerId","label","authMode","availability","hasSetupSkill"],header:"MCP connector providers",emptyMessage:"No MCP connector providers found."},Ant={providerId:{label:"Provider",type:{kind:"string"}},setupSkill:{label:"Setup skill",type:{kind:"string"}}},tnt={layout:"field-list",schema:Ant,fields:["providerId","setupSkill"],title:"MCP connector setup skill"},Lo=(A)=>{let t=A.json,g=P({tokenFlag:A.token,jsonMode:t});return{client:z({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:t}),json:t,projectId:g.projectId}},Zy=(A,t)=>({...A,url:pyA(t,A.connectionId)}),gnt=3000,nnt=async(A)=>{let{values:t}=S(A,{...f,"project-id":{type:"string"},"connected-only":{type:"boolean"}}),{client:g,json:i,projectId:n}=Lo(t),{connectors:Q}=N(await g.mcpConnectors.list({projectId:t["project-id"],connectedOnly:t["connected-only"]}),"Couldn't list MCP connectors (check the active project and try again)",i),o=dg(t["project-id"]??n,i);j(xgt,Q.map((B)=>Zy(B,o)),{json:i})},int=async(A)=>{let{values:t,positionals:g}=S(A,{...f,"project-id":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return b("Connection ID is required.");return r("Connection ID is required.")}let{client:n,json:Q,projectId:o}=Lo(t),{connector:B}=N(await n.mcpConnectors.get({connectionId:i,projectId:t["project-id"]}),"Couldn't get MCP connector (run 'sazabi mcp-connectors list' to see connection IDs)",Q),h=dg(t["project-id"]??o,Q);X(ON,Zy(B,h),{json:Q})},Qnt=async(A)=>{let{values:t,positionals:g}=S(A,{...f,"project-id":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return b("Connection ID is required.");return r("Connection ID is required.")}let{client:n,json:Q,projectId:o}=Lo(t),{connector:B,tools:h}=N(await n.mcpConnectors.details({connectionId:i,projectId:t["project-id"]}),"Couldn't inspect MCP connector (run 'sazabi mcp-connectors list' to see connection IDs)",Q),e=dg(t["project-id"]??o,Q),C=Zy(B,e);if(Q){Z({connector:C,tools:h});return}X(ON,C,{json:Q}),j(dgt,h,{json:Q})},ont=async(A)=>{let{values:t}=S(A,{...f}),{client:g,json:i}=Lo(t),{providers:n}=N(await g.mcpConnectors.listProviders(),"Couldn't list MCP connector providers (try again)",i),Q=n.map((o)=>({providerId:o.providerId,label:o.label,authMode:o.authMode,availability:o.availability,hasSetupSkill:Boolean(o.setupSkill)}));j(sgt,Q,{json:i})},Int=async(A)=>{let{values:t}=S(A,{...f,"provider-id":{type:"string"}});if(!t["provider-id"]){if(t.json)return b("--provider-id is required.");return r("--provider-id is required. Use 'sazabi mcp-connectors providers' to see valid provider IDs.")}let{client:g,json:i}=Lo(t),{providers:n}=N(await g.mcpConnectors.listProviders(),"Couldn't list MCP connector providers (try again)",i),Q=n.find((o)=>o.providerId===t["provider-id"]);if(!Q){let o=`Unknown MCP connector provider: '${t["provider-id"]}'. Run 'sazabi mcp-connectors providers' to see valid provider IDs.`;if(i)return b(o);return r(o)}if(!Q.setupSkill){if(i)return b(`No setup skill available for ${t["provider-id"]}.`);return r(`No setup skill available for ${t["provider-id"]}. This MCP connector does not have an agent-ready skill yet.`)}X(tnt,{providerId:t["provider-id"],setupSkill:Q.setupSkill},{json:i})},Bnt=async(A)=>{let{values:t,positionals:g}=S(A,{...f,"project-id":{type:"string"},"server-url":{type:"string"},scopes:{type:"string"},"read-only":{type:"boolean"}},{allowPositionals:!0}),i=t.json,n=g[0];if(!n){if(i)return b("Provider ID is required. Run 'sazabi mcp-connectors providers' to see available providers.");return r("Provider ID is required. Run 'sazabi mcp-connectors providers' to see available providers.")}let{client:Q,projectId:o}=Lo(t),B=t.scopes,h=B?B.split(",").map((C)=>C.trim()).filter(Boolean):void 0,e=N(await Q.mcpConnectors.beginOAuthInstall({providerId:n,projectId:t["project-id"],serverUrl:t["server-url"],requestedScopes:h,readOnly:t["read-only"]}),`Couldn't start the OAuth install flow for '${n}'`,i);if(i){Z({authorizationUrl:e.authorizationUrl,connectionId:e.connectionId,expiresAt:e.expiresAt});return}await xwA({client:Q,providerId:n,begin:e,projectId:t["project-id"]??o})},mwA=async(A)=>{let{client:t,providerId:g,projectId:i}=A,n=N(await t.mcpConnectors.beginOAuthInstall({providerId:g,projectId:i}),`Couldn't start the OAuth install flow for '${g}'`,!1);await xwA({client:t,providerId:g,begin:n,projectId:i})},xwA=async(A)=>{let{client:t,providerId:g,begin:i,projectId:n}=A;rA(`Connect ${g}`),H("Complete the authorization in a browser where you're signed in to the Sazabi dashboard."),H(`Opening ${d.info(i.authorizationUrl)}`),DQ(i.authorizationUrl),H("Waiting for the browser flow to complete...");let Q=new Date(i.expiresAt).getTime()+15000;while(Date.now()<Q){await Oi(gnt);let o=N(await t.mcpConnectors.getOAuthInstallAttempt({connectionId:i.connectionId,projectId:n}),"Couldn't poll the install attempt (try again)",!1);if(o.status==="authorizing")continue;if(o.status==="connected"){if(o.connector){O(`Connected ${o.connector.displayName}.`);let B=dg(n,!1);X(ON,Zy(o.connector,B),{json:!1})}else O(`Connected ${g}.`);return}return r(`Connect failed. The provider returned an error. Run 'sazabi mcp-connectors connect ${g}' again.`)}return r("The browser flow didn't complete in time. Run the command again.")},hnt=async(A)=>{let{values:t,positionals:g}=S(A,{...f,"project-id":{type:"string"}},{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return b("Connection ID is required.");return r("Connection ID is required. Run 'sazabi mcp-connectors list' to see connection IDs.")}let{client:Q}=Lo(t);if(N(await Q.mcpConnectors.disconnect({connectionId:i,projectId:t["project-id"]}),"Couldn't disconnect the MCP connector",n),n){Z({success:!0});return}O("MCP connector disconnected.")},ent=async(A)=>{let{values:t,positionals:g}=S(A,{...f,"project-id":{type:"string"},"server-url":{type:"string"},transport:{type:"string"},headers:{type:"string"},"aws-sig-v4":{type:"string"}},{allowPositionals:!0}),i=g[0],n=t.json;if(!i){if(n)return b("Connection ID is required.");return r("Connection ID is required. Run 'sazabi mcp-connectors list' to see connection IDs.")}let Q=t["server-url"],o=t.transport,B,h=t.headers;if(h)try{let a=JSON.parse(h);if(!Array.isArray(a))throw Error("not an array");B=a}catch{if(n)return b(`--headers must be a JSON array, e.g. '[{"id":"auth","name":"Authorization","value":"Bearer ..."}]'`);return r(`--headers must be a JSON array, e.g. '[{"id":"auth","name":"Authorization","value":"Bearer ..."}]'`)}let e,C=t["aws-sig-v4"];if(C)try{let a=JSON.parse(C);if(typeof a!=="object"||a===null||Array.isArray(a))throw Error("not an object");e=a}catch{if(n)return b(`--aws-sig-v4 must be a JSON object, e.g. '{"accessKeyId":"...","secretAccessKey":"...","region":"us-east-1"}'`);return r(`--aws-sig-v4 must be a JSON object, e.g. '{"accessKeyId":"...","secretAccessKey":"...","region":"us-east-1"}'`)}if(!Q&&!o&&!B&&!e){if(n)return b("At least one of --server-url, --transport, --headers, or --aws-sig-v4 is required.");return r("At least one of --server-url, --transport, --headers, or --aws-sig-v4 is required.")}let{client:c,projectId:E}=Lo(t),{connector:y}=N(await c.mcpConnectors.update({connectionId:i,projectId:t["project-id"],...Q?{serverUrl:Q}:{},...o?{transport:o}:{},...B?{headers:B}:{},...e?{awsSigV4:e}:{}}),"Couldn't update the MCP connector (check the values and try again)",n);if(!n)O("MCP connector updated.");let w=dg(t["project-id"]??E,n);X(ON,Zy(y,w),{json:n})},qwA=QA("mcp-connectors","Inspect MCP connectors").withSubcommands({list:U("list","List configured MCP connectors",nnt).withOptions({...R,"project-id":{type:"string",description:"Project ID"},"connected-only":{type:"boolean",description:"Only show connected connectors"}}).withExamples(["sazabi mcp-connectors list # List all connectors","sazabi mcp-connectors list --connected-only # Only connected ones","sazabi mcp-connectors list --json # Output as JSON"]).build(),get:U("get","Get one MCP connector",int).withPositionalArgs("<connection-id>").withOptions({...R,"project-id":{type:"string",description:"Project ID"}}).withExamples(["sazabi mcp-connectors get <id> # Show connector details"]).build(),details:U("details","Inspect one connector's tool surface",Qnt).withPositionalArgs("<connection-id>").withOptions({...R,"project-id":{type:"string",description:"Project ID"}}).withExamples(["sazabi mcp-connectors details <id> # Show enabled tools","sazabi mcp-connectors details <id> --json # Output as JSON"]).build(),providers:U("providers","List all supported MCP connector providers",ont).withOptions({...R}).withExamples(["sazabi mcp-connectors providers # List all providers","sazabi mcp-connectors providers --json # Output as JSON"]).build(),skill:U("skill","Show setup skill for an MCP connector provider",Int).withOptions({...R,"provider-id":{type:"string",description:"MCP connector provider ID (e.g. linear, supabase)"}}).withExamples(["sazabi mcp-connectors skill --provider-id linear # Show Linear setup skill","sazabi mcp-connectors skill --provider-id posthog # Show PostHog setup skill","sazabi mcp-connectors skill --provider-id x --json # Output as JSON"]).build(),connect:U("connect","Connect an MCP provider via an OAuth browser flow",Bnt).withPositionalArgs("<provider-id>").withOptions({...R,"project-id":{type:"string",description:"Project to install the connector into"},"server-url":{type:"string",description:"Server URL for multi-region providers (defaults to the provider primary)"},scopes:{type:"string",description:"Comma-separated OAuth scopes to request (defaults to provider recommended set)"},"read-only":{type:"boolean",description:"Restrict the connector to read-only tools after install"}}).withExamples(["sazabi mcp-connectors connect linear # Connect Linear via OAuth","sazabi mcp-connectors connect slack --read-only # Read-only Slack connector","sazabi mcp-connectors connect linear --json # Return auth URL as JSON"]).build(),disconnect:U("disconnect","Disconnect an MCP connector",hnt).withPositionalArgs("<connection-id>").withOptions({...R,"project-id":{type:"string",description:"Project ID"}}).withExamples(["sazabi mcp-connectors disconnect <id> # Remove the connector"]).build(),"update-credentials":U("update-credentials","Update a custom connector's server URL, transport, or headers",ent).withPositionalArgs("<connection-id>").withOptions({...R,"project-id":{type:"string",description:"Project ID"},"server-url":{type:"string",description:"New MCP server URL"},transport:{type:"string",description:"New transport protocol (sse | streamable-http | stdio)"},headers:{type:"string",description:`Replacement header set as JSON array, e.g. '[{"id":"auth","name":"Authorization","value":"Bearer ..."}]'`},"aws-sig-v4":{type:"string",description:`AWS SigV4 credentials as JSON, e.g. '{"accessKeyId":"...","secretAccessKey":"...","region":"us-east-1"}'`}}).withExamples(["sazabi mcp-connectors update-credentials <id> --server-url https://new.example.com/mcp # Update server URL",`sazabi mcp-connectors update-credentials <id> --headers '[{"id":"auth","name":"Authorization","value":"Bearer ..."}]' # Replace headers`]).build()}).withExamples(["sazabi mcp-connectors list # List configured MCP connectors","sazabi mcp-connectors get <id> # Inspect one connector","sazabi mcp-connectors details <id> # Inspect a connector's tool surface","sazabi mcp-connectors providers # List all MCP connector providers","sazabi mcp-connectors connect linear # Connect Linear via OAuth","sazabi mcp-connectors disconnect <id> # Remove a connector","sazabi mcp-connectors update-credentials <id> --server-url https://... # Update server URL","sazabi mcp-connectors skill --provider-id linear # Show setup skill"]).build();nA();aA();IA();var dwA={membershipId:{label:"Membership ID",type:{kind:"string"}},userId:{label:"User ID",type:{kind:"string"}},name:{label:"Name",type:{kind:"nullable-string"}},email:{label:"Email",type:{kind:"string"}},role:{label:"Role",type:{kind:"string"}}},Cnt={schema:dwA,columns:["membershipId","userId","name","email","role"],header:"Members",emptyMessage:"No members found."},cnt={layout:"field-list",schema:dwA,fields:["membershipId","userId","name","email","role"]},Ent={id:{label:"ID",type:{kind:"string"}},email:{label:"Email",type:{kind:"string"}},role:{label:"Role",type:{kind:"string"}},status:{label:"Status",type:{kind:"string"}},expiresAt:{label:"Expires",type:{kind:"string"}}},pwA={schema:Ent,columns:["id","email","role","status","expiresAt"],header:"Invitations",emptyMessage:"No pending invitations."},ynt=async(A)=>{let t=P({tokenFlag:A.token,organizationIdFlag:A.organizationId,jsonMode:A.json}),g=z({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=N(await g.members.list({organizationId:t.organizationId}),"Couldn't list members (check the active organization and try again)",A.json);j(Cnt,i.members,{json:A.json})},Dnt=async(A,t)=>{let g=P({tokenFlag:t.token,organizationIdFlag:t.organizationId,jsonMode:t.json}),i=z({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=N(await i.members.updateRole(A,t.role,g.organizationId),"Failed to update member role",t.json);X(cnt,n.member,{json:t.json})},wnt=async(A,t)=>{let g=P({tokenFlag:t.token,organizationIdFlag:t.organizationId,jsonMode:t.json}),i=z({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=N(await i.members.remove(A,g.organizationId),"Failed to remove member",t.json);if(t.json){Z(n);return}O(`Member ${n.removedUserId} removed from the active organization.`)},WO=async(A)=>{let t=[];for(let g of A.emails){let i=N(await A.client.members.invite({email:g,role:A.role,organizationId:A.organizationId}),`Failed to invite ${g}`,A.json);t.push(i.invitation)}return t},ant=async(A)=>{let t=P({tokenFlag:A.token,organizationIdFlag:A.organizationId,jsonMode:A.json}),g=z({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=await WO({client:g,emails:A.emails,role:A.role,organizationId:t.organizationId,json:A.json});j(pwA,i,{json:A.json})},rnt=async(A)=>{let t=P({tokenFlag:A.token,organizationIdFlag:A.organizationId,jsonMode:A.json}),g=z({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json}),i=N(await g.members.listInvitations(t.organizationId),"Couldn't list invitations (check the active organization and try again)",A.json);j(pwA,i.invitations,{json:A.json})},bnt=async(A,t)=>{let g=P({tokenFlag:t.token,organizationIdFlag:t.organizationId,jsonMode:t.json}),i=z({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl,jsonMode:t.json}),n=N(await i.members.revokeInvitation({invitationId:A,organizationId:g.organizationId}),"Failed to revoke invitation",t.json);if(t.json){Z(n);return}O(`Invitation ${n.revokedInvitationId} revoked.`)},swA=QA("members","Manage organization members").withSubcommands({list:U("list","List members in the active organization",async(A)=>{let{values:t,positionals:g}=S(A,{token:{type:"string"},"organization-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0});if(g.length>0){let i=g.join(", ");if(t.json)return b(`Unexpected arguments: ${i}. Run 'sazabi members -h' for usage.`);return r(`Unexpected arguments: ${i}. Run 'sazabi members -h' for usage.`)}await ynt({token:t.token,organizationId:t["organization-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi members list # List members in the active organization"]).build(),"update-role":U("update-role","Update one member's organization role",async(A)=>{let{values:t,positionals:g}=S(A,{token:{type:"string"},"organization-id":{type:"string"},role:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return b("User ID is required.");return r("User ID is required.")}if(t.role!=="admin"&&t.role!=="member"){if(t.json)return b("Role must be either 'admin' or 'member'.");return r("Role must be either 'admin' or 'member'.")}await Dnt(i,{token:t.token,organizationId:t["organization-id"],role:t.role,json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},role:{type:"string",description:"New role: admin or member"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi members update-role user_123 --role admin # Promote a member to admin"]).build(),remove:U("remove","Remove one member from the active organization",async(A)=>{let{values:t,positionals:g}=S(A,{token:{type:"string"},"organization-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return b("User ID is required.");return r("User ID is required.")}await wnt(i,{token:t.token,organizationId:t["organization-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi members remove user_123 # Remove a member by user ID","sazabi members remove alex@example.com # Remove a member by email"]).build(),invite:U("invite","Invite one or more people to the active organization by email",async(A)=>{let{values:t,positionals:g}=S(A,{token:{type:"string"},"organization-id":{type:"string"},email:{type:"string",multiple:!0},role:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0});if(g.length>0){let o=`Unexpected arguments: ${g.join(", ")}. Pass emails with --email. Run 'sazabi members -h' for usage.`;if(t.json)return b(o);return r(o)}let i=t.email??[];if(i.length===0){if(t.json)return b("At least one --email is required.");return r("At least one --email is required.")}let n=t.role??"member";if(n!=="admin"&&n!=="member"){if(t.json)return b("Role must be either 'admin' or 'member'.");return r("Role must be either 'admin' or 'member'.")}await ant({emails:i,role:n,token:t.token,organizationId:t["organization-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},email:{type:"string",description:"Email address to invite (repeatable)"},role:{type:"string",description:"Role to grant: admin or member (default member)"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi members invite --email alex@example.com # Invite one person as a member","sazabi members invite --email a@example.com --email b@example.com --role admin # Invite several as admins"]).build(),"list-invitations":U("list-invitations","List pending invitations in the active organization",async(A)=>{let{values:t,positionals:g}=S(A,{token:{type:"string"},"organization-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0});if(g.length>0){let i=g.join(", ");if(t.json)return b(`Unexpected arguments: ${i}. Run 'sazabi members -h' for usage.`);return r(`Unexpected arguments: ${i}. Run 'sazabi members -h' for usage.`)}await rnt({token:t.token,organizationId:t["organization-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi members list-invitations # List pending invitations"]).build(),"revoke-invitation":U("revoke-invitation","Revoke one pending invitation in the active organization",async(A)=>{let{values:t,positionals:g}=S(A,{token:{type:"string"},"organization-id":{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return b("Invitation ID is required.");return r("Invitation ID is required.")}await bnt(i,{token:t.token,organizationId:t["organization-id"],json:t.json,apiBaseUrl:t["api-base-url"]})}).withOptions({token:{type:"string",description:"Override token"},"organization-id":{type:"string",description:"Override organization selection"},json:{type:"boolean",description:"Output as JSON"},"api-base-url":{type:"string",description:"Override API base URL"}}).withExamples(["sazabi members revoke-invitation invitation_123 # Revoke a pending invitation"]).build()}).withExamples(["sazabi members list # List members in the active organization","sazabi members invite --email alex@example.com # Invite a person by email","sazabi members update-role user_123 --role admin # Promote a member to admin","sazabi members remove alex@example.com # Remove a member by user ID or email","sazabi members list-invitations # List pending invitations","sazabi members revoke-invitation invitation_123 # Revoke a pending invitation"]).build();nA();HI();import{readFile as Nnt}from"node:fs/promises";aA();IA();var unt=/^(\d+)(s|m|h|d)$/u,XO=(A)=>({id:A.id,projectId:A.projectId,kind:A.kind,managed:A.managed,path:A.path,title:A.title,contentHash:A.contentHash,body:"body"in A?A.body:null,createdAt:A.createdAt,updatedAt:A.updatedAt}),AaA=(A)=>({documentId:A.documentId,kind:A.kind,managed:A.managed,path:A.path,title:A.title,snippet:A.snippet,score:A.score}),iaA={id:{label:"ID",type:{kind:"id"}},projectId:{label:"Project ID",type:{kind:"id"}},kind:{label:"Kind",type:{kind:"string"}},managed:{label:"Managed",type:{kind:"boolean"}},path:{label:"Path",type:{kind:"nullable-string"}},title:{label:"Title",type:{kind:"nullable-string"}},contentHash:{label:"Content hash",type:{kind:"string"}},body:{label:"Body",type:{kind:"custom",render:(A)=>A?String(A):"(empty)",serialize:(A)=>A}},createdAt:{label:"Created at",type:{kind:"date"}},updatedAt:{label:"Updated at",type:{kind:"date"}}},Unt={documentId:{label:"Document ID",type:{kind:"id"}},kind:{label:"Kind",type:{kind:"string"}},managed:{label:"Managed",type:{kind:"boolean"}},path:{label:"Path",type:{kind:"nullable-string"}},title:{label:"Title",type:{kind:"nullable-string"}},snippet:{label:"Snippet",type:{kind:"string"}},score:{label:"Score",type:{kind:"number"}}},Fnt={schema:iaA,columns:["path","kind","title","updatedAt"],jsonFields:["id","projectId","kind","managed","path","title","updatedAt"],header:"Memory",emptyMessage:"No memory documents found."},QaA={layout:"field-list",schema:iaA,fields:["id","projectId","kind","managed","path","title","contentHash","body","createdAt","updatedAt"],title:"Memory document"},Lnt={schema:Unt,columns:["path","kind","snippet","score"],jsonFields:["documentId","kind","managed","path","title","snippet","score"],header:"Memory search results",emptyMessage:"No matching memory documents found."},Xy=(A)=>{let t=P({tokenFlag:A.token,projectIdFlag:A.projectId,jsonMode:A.json});return{client:z({token:t.token,organizationId:t.organizationId,projectId:t.projectId,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:A.json})}},Snt=async()=>{let A=[];process.stdin.setEncoding("utf8");for await(let t of process.stdin)A.push(String(t));return A.join("")},VO=(A)=>{let t=A.join("/").trim();return t.length>0?t:void 0},lnt=(A,t)=>{if(!unt.test(A.trim())){if(t){b("Duration must use s, m, h, or d units, for example 7d or 30m.");return}r("Duration must use s, m, h, or d units, for example 7d or 30m.");return}return A.trim()},Mnt=(A,t)=>{if(A===void 0)return;try{return cy.parse(A),A.trim()}catch{if(t){b("Kind filter must be a comma-separated list of note, runbook, or change.");return}r("Kind filter must be a comma-separated list of note, runbook, or change.");return}},Ynt=(A,t)=>{if(A===void 0)return;let g=A.trim().toLowerCase();if(g==="true")return!0;if(g==="false")return!1;let i='Invalid --managed value. Expected "true" or "false".';if(t){b(i);return}r(i);return},$nt=async(A,t)=>{let g=A.body!==void 0,i=A.file!==void 0;if(g&&i){if(A.json){b("Provide memory body via exactly one of --body or --file.");return}r("Provide memory body via exactly one of --body or --file.");return}if(!g&&!i){if(!t)return;let Q="Memory body is required. Provide --body <text> or --file <path>.";if(A.json){b(Q);return}r(Q);return}if(g)return A.body;let n=A.file;try{return n==="-"?await Snt():await Nnt(n,"utf8")}catch(Q){let o=`Couldn't read memory body (check that the --file path exists and is readable): ${Q instanceof Error?Q.message:String(Q)}`;if(A.json){b(o);return}r(o);return}},oaA=(A)=>({...A.kind!==void 0?{kind:A.kind}:{},...A.since!==void 0?{since:A.since}:{},...A.pathPrefix!==void 0?{pathPrefix:A.pathPrefix}:{},...A.managed!==void 0?{managed:A.managed}:{},...A.service!==void 0?{service:A.service}:{}}),knt=async(A)=>{let{client:t}=Xy(A),g=N(await t.memory.list({...oaA(A),...A.limit!==void 0?{limit:A.limit}:{},...A.cursor!==void 0?{cursor:A.cursor}:{}}),"Couldn't list memory (check the active project and try again)",A.json);j(Fnt,g.documents.map(XO),{json:A.json,nextCursor:g.nextCursor})},Gnt=async(A)=>{let{client:t}=Xy(A),g=N(await t.memory.get({...A.id!==void 0?{id:A.id}:{},...A.path!==void 0?{path:A.path}:{}}),"Couldn't get memory document (run 'sazabi memory list' to see paths)",A.json);X(QaA,XO(g.document),{json:A.json})},Jnt=async(A)=>{let{client:t}=Xy(A),g=N(await t.memory.search({query:A.query,...oaA(A),...A.limit!==void 0?{limit:A.limit}:{}}),"Couldn't search memory (check the active project and try again)",A.json);if(A.json){Z({hits:g.hits.map(AaA),emptyVerdict:g.emptyVerdict});return}j(Lnt,g.hits.map(AaA),{json:!1})},Tnt=async(A)=>{let t=await $nt(A,!0);if(t===void 0)return;let{client:g}=Xy(A),i=N(await g.memory.put({path:A.path,body:t,kind:A.kind??"note",...A.title!==void 0?{title:A.title}:{}}),"Couldn't write memory document (check the path and body, then try again)",A.json);if(!A.json){let n=i.document.path??i.document.id;O(`Memory document "${n}" saved.`)}X(QaA,XO(i.document),{json:A.json})},Rnt=async(A)=>{let{client:t}=Xy(A);if(N(await t.memory.delete({...A.id!==void 0?{id:A.id}:{},...A.path!==void 0?{path:A.path}:{}}),"Couldn't delete memory document (run 'sazabi memory list' to see paths)",A.json),A.json){Z({deleted:!0,...A.id!==void 0?{id:A.id}:{},...A.path!==void 0?{path:A.path}:{}});return}let g=A.path??A.id??"document";O(`Memory document "${g}" deleted.`)},Wy={...f,"project-id":{type:"string"}},Vy={...R,"project-id":{type:"string",description:"Override active project ID"}},taA={kind:{type:"string"},since:{type:"string"},"path-prefix":{type:"string"},managed:{type:"string"},service:{type:"string"}},gaA={kind:{type:"string",description:"Comma-separated kinds: note, runbook, or change"},since:{type:"string",description:"Only documents updated within this window, for example 7d"},"path-prefix":{type:"string",description:"Filter to paths starting with this prefix"},managed:{type:"string",description:'Filter managed documents: "true" or "false"'},service:{type:"string",description:"Filter to documents whose attrs.services contains this value"}},Pnt=(A,t)=>{if(A===void 0)return;let g=Number(A);if(!Number.isInteger(g)||g<1||g>100){if(t){b("Invalid --limit value. Expected an integer between 1 and 100.");return}r("Invalid --limit value. Expected an integer between 1 and 100.");return}return g},fnt=(A,t)=>{if(A===void 0)return;let g=Number(A);if(!Number.isInteger(g)||g<1||g>50){if(t){b("Invalid --limit value. Expected an integer between 1 and 50.");return}r("Invalid --limit value. Expected an integer between 1 and 50.");return}return g},naA=(A)=>{let t=Mnt(A.kind,A.json);if(A.kind!==void 0&&t===void 0)return;let g;if(A.since!==void 0){if(g=lnt(A.since,A.json),g===void 0)return}let i=Ynt(A.managed,A.json);if(A.managed!==void 0&&i===void 0)return;return{kind:t,since:g,pathPrefix:A["path-prefix"],managed:i,service:A.service}},znt=(A,t)=>{if(A===void 0)return;if(A==="note"||A==="runbook")return A;let g='Invalid --kind value. Expected "note" or "runbook".';if(t){b(g);return}r(g);return},IaA=QA("memory","Read, search, and update durable project memory").withSubcommands({list:U("list","List project memory catalog rows",async(A)=>{let{values:t}=S(A,{...Wy,...taA,limit:{type:"string"},cursor:{type:"string"}}),g=naA(t);if(g===void 0)return;let i=Pnt(t.limit,t.json);if(t.limit!==void 0&&i===void 0)return;await knt({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],...g,limit:i,cursor:t.cursor})}).withOptions({...Vy,...gaA,limit:{type:"string",description:"Maximum number of documents to return (default: 50, max: 100)"},cursor:{type:"string",description:"Pagination cursor from previous response"}}).withExamples(["sazabi memory list # List project memory","sazabi memory list --kind note,runbook # Filter by kind","sazabi memory list --kind change --since 7d --path-prefix services/durable-agent # Recent durable-agent changes","sazabi memory list --service intake --limit 50 --json # List intake-tagged docs as JSON","sazabi memory list --managed false # List user-managed docs only"]).build(),get:U("get","Get one project memory document (prefer --json for agents)",async(A)=>{let{values:t,positionals:g}=S(A,{...Wy,id:{type:"string"}},{allowPositionals:!0}),i=VO(g);if(t.id!==void 0===(i!==void 0)){if(t.json)return b("Provide exactly one of a path or --id.");return r("Provide exactly one of a path or --id.")}await Gnt({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],id:t.id,path:i})}).withPositionalArgs("[path]").withOptions({...Vy,id:{type:"string",description:"Document id"}}).withExamples(["sazabi memory get AGENTS.md # Get by curated path","sazabi memory get notes/architecture.md --json # Get one document as JSON","sazabi memory get --id 22222222-2222-4222-8222-222222222222 # Get by document id"]).build(),search:U("search","Search project memory documents",async(A)=>{let{values:t,positionals:g}=S(A,{...Wy,...taA,limit:{type:"string"}},{allowPositionals:!0}),i=g.join(" ").trim();if(!i){if(t.json)return b("Search query is required.");return r("Search query is required.")}let n=naA(t);if(n===void 0)return;let Q=fnt(t.limit,t.json);if(t.limit!==void 0&&Q===void 0)return;await Jnt({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],query:i,...n,limit:Q})}).withPositionalArgs("<query>").withOptions({...Vy,...gaA,limit:{type:"string",description:"Maximum number of hits to return (default: 10, max: 50)"}}).withExamples(['sazabi memory search "where is llm-config wired" --kind change --json # Search recent changes','sazabi memory search "known benign noise" --kind note,runbook # Search curated guidance','sazabi memory search "pooler timeout" --since 30d --service api # Search api-tagged docs','sazabi memory search "pooler timeout" --managed true --kind change # Search managed changes']).build(),put:U("put","Create or replace a curated memory document",async(A)=>{let{values:t,positionals:g}=S(A,{...Wy,body:{type:"string"},file:{type:"string"},kind:{type:"string"},title:{type:"string"}},{allowPositionals:!0}),i=VO(g);if(!i){if(t.json)return b("Memory path is required.");return r("Memory path is required.")}let n=znt(t.kind,t.json);if(t.kind!==void 0&&n===void 0)return;await Tnt({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],path:i,body:t.body,file:t.file,kind:n,title:t.title})}).withPositionalArgs("<path>").withOptions({...Vy,body:{type:"string",description:"Document body text"},file:{type:"string",description:"Read document body from a file, or '-' for stdin"},kind:{type:"string",description:'Curated kind: "note" (default) or "runbook"'},title:{type:"string",description:"Optional display title"}}).withExamples(["sazabi memory put AGENTS.md --file ./AGENTS.md # Upsert from a local file",'sazabi memory put notes/customer-context.md --body "…" --kind note # Upsert inline note body']).build(),delete:U("delete","Delete a curated memory document",async(A)=>{let{values:t,positionals:g}=S(A,{...Wy,id:{type:"string"}},{allowPositionals:!0}),i=VO(g);if(t.id!==void 0===(i!==void 0)){if(t.json)return b("Provide exactly one of a path or --id.");return r("Provide exactly one of a path or --id.")}await Rnt({token:t.token,projectId:t["project-id"],json:t.json,apiBaseUrl:t["api-base-url"],id:t.id,path:i})}).withPositionalArgs("[path]").withOptions({...Vy,id:{type:"string",description:"Document id"}}).withExamples(["sazabi memory delete notes/stale.md # Delete a curated document"]).build()}).withExamples(["sazabi memory get AGENTS.md # Get the index doc","sazabi memory list --kind note,runbook # Browse curated docs",'sazabi memory search "pooler timeout" --since 30d # Semantic search',"sazabi memory put AGENTS.md --file ./AGENTS.md # Upsert a curated doc","sazabi memory delete notes/stale.md # Delete a curated doc"]).build();nA();aA();IA();nA();aA();IA();IA();var Ont=2000,vN=async(A)=>{let t=A.pollIntervalMs??Ont,g=Date.now(),i=!1,n={completed:!1,threadId:A.threadId,runId:A.runId,status:"processing",response:null};while(!0){let Q=await A.client.runs.get(A.runId);if(!Q.success){if(!Znt(Q))return HO(A.printProgress,i),Q}else if(n=Q.value,Q.value.completed)return HO(A.printProgress,i),Q;if(A.timeoutMs!==void 0&&Date.now()-g>=A.timeoutMs)return HO(A.printProgress,i),ut(n);i=vnt(A.printProgress,i),await Oy(t)}},vnt=(A,t)=>{if(!A)return t;if(!t)process.stdout.write(`
|
|
8767
8767
|
`);return process.stdout.write("."),!0},HO=(A,t)=>{if(!A||!t)return;process.stdout.write(`
|
|
8768
|
-
`)},Znt=(A)=>{return A.statusCode===404};var Wnt={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:(A)=>A.threadUrl??null},runId:{label:"Run ID",type:{kind:"id"}},status:{label:"Status",type:{kind:"string"}},pollWith:{label:"Poll with",type:{kind:"string"},get:(A)=>`sazabi runs get ${A.runId}`},response:{label:"Response",type:{kind:"nullable-string"},get:(A)=>A.response}},Vnt={layout:"sections",schema:Wnt,primary:{title:"Thread",fields:["threadId","messageId","url","runId","status","pollWith"]},secondary:[{title:"Response",field:"response"}]},BaA=()=>{return process.env.SAZABI_AUTOMATION_ID??process.env.SAZABI_SCRIPT_PARAM_AUTOMATION_ID},haA=()=>process.env.SAZABI_AMBIENT_SERVICE_RUN==="true"?!0:void 0,KO=async(A)=>{let t=Date.now(),g=A.waitTimeoutSeconds===void 0?void 0:A.waitTimeoutSeconds*1000,i=await caA({message:A.message,threadId:A.threadId,projectId:A.projectId,json:A.json,client:A.client,wait:!0,timeoutMs:g,automationId:A.automationId,ambientServiceRun:A.ambientServiceRun});if(i.status==="processing"){let n=g===void 0?void 0:Math.max(0,g-(Date.now()-t)),Q=N(await vN({client:A.client,runId:i.runId,threadId:i.threadId,timeoutMs:n,printProgress:!A.json}),`Couldn't get run (poll again with 'sazabi runs get ${i.runId}')`,A.json);i={...i,status:Q.status,response:Q.response,messageId:i.messageId??Q.messageId}}return i},CaA=async(A,t={})=>{let g=P({tokenFlag:t.token,jsonMode:t.json}),i=z({token:g.token,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl}),n=t.wait?await KO({client:i,message:A,threadId:t.threadId,projectId:g.projectId,waitTimeoutSeconds:t.timeout===void 0?void 0:t.timeout/1000,json:t.json,automationId:BaA(),ambientServiceRun:haA()}):await caA({message:A,threadId:t.threadId,projectId:g.projectId,json:t.json,client:i,wait:!1,timeoutMs:t.timeout,automationId:BaA(),ambientServiceRun:haA()});X(Vnt,n,{json:t.json})},caA=async(A)=>{if(A.threadId){let g=N(await A.client.messages.append(A.threadId,A.message,A.wait??!1,eaA(A.timeoutMs),A.automationId,A.ambientServiceRun),"Failed to send message",A.json);return{threadId:A.threadId,runId:g.result.runId,messageId:g.result.messageId,status:g.result.status,response:g.result.response,threadUrl:A.projectId?Ot(A.projectId,A.threadId,void 0,g.result.messageId):void 0}}let t=N(await A.client.threads.create({message:A.message,...A.projectId?{projectId:A.projectId}:{},wait:A.wait??!1,timeoutSeconds:eaA(A.timeoutMs),...A.automationId!==void 0?{automationId:A.automationId}:{},...A.ambientServiceRun?{ambientServiceRun:!0}:{}}),"Failed to create thread",A.json);return{threadId:t.result.threadId,runId:t.result.runId,messageId:t.result.messageId,status:t.result.status,response:t.result.response,threadUrl:A.projectId?Ot(A.projectId,t.result.threadId,void 0,t.result.messageId):void 0}},eaA=(A)=>{if(A===void 0)return 20;return Math.max(1,Math.min(Math.ceil(A/1000),20))};var Xnt={id:{label:"ID",type:{kind:"string"}},role:{label:"Role",type:{kind:"role"}},content:{label:"Content",type:{kind:"custom",render:(A)=>{let g=A.find((i)=>i.type==="message"&&Boolean(i.message));return g?Pg(g.message):eg("(no text)")}}},createdAt:{label:"Created",type:{kind:"date"}}},Hnt={schema:Xnt,columns:["id","role","content","createdAt"],header:"Messages",emptyMessage:"No messages found."},Knt={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:(A)=>Pg(A)}},score:{label:"Score",align:"right",type:{kind:"custom",render:(A)=>A!=null?A.toFixed(2):"-"}}},jnt={schema:Knt,columns:["id","threadTitle","role","content","score"],header:{title:"Search results",variant:"search"},emptyMessage:"No matching messages found."},_nt=async(A,t)=>{let g=P({tokenFlag:t.token,jsonMode:t.json}),i=z({token:g.token,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl}),{messages:n,nextCursor:Q}=N(await i.messages.list(A,{limit:t.limit,cursor:t.cursor}),"Couldn't list messages (check the thread ID and try again)",t.json);j(Hnt,n,{json:t.json,nextCursor:Q})},mnt=async(A,t)=>{let g=P({tokenFlag:t.token,jsonMode:t.json}),i=z({token:g.token,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl}),{messages:n,pagination:Q}=N(await i.search.messages({query:A,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){Z({messages:n,pagination:Q});return}j(jnt,n,{count:Q.totalResults}),Hi({type:"page",page:Q.page,totalPages:Q.totalPages})},EaA=QA("messages","Send, list, and search messages").withSubcommands({send:U("send","Send a message (creates new thread if --thread-id omitted)",async(A)=>{let{values:t,positionals:g}=S(A,{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}),i=g.join(" ");if(!i){if(t.json)return b("Message is required. Usage: sazabi messages send <message> [--thread-id <id>]");return r("Message is required. Usage: sazabi messages send <message> [--thread-id <id>]")}let n=t.timeout?Cg(t.timeout,1,3600,"Timeout",t.json)*1000:void 0,Q={token:t.token,threadId:t["thread-id"],wait:t.wait,timeout:n,json:t.json,apiBaseUrl:t["api-base-url"]};await CaA(i,Q)}).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:U("list","List messages in a thread",async(A)=>{let{values:t,positionals:g}=S(A,{token:{type:"string"},limit:{type:"string"},cursor:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return b("Thread ID is required. Usage: sazabi messages list <thread-id>");return r("Thread ID is required. Usage: sazabi messages list <thread-id>")}if(g.length>1){let Q=g.slice(1).join(", ");if(t.json)return b(`Unexpected arguments: ${Q}. Run 'sazabi messages -h' for usage.`);return r(`Unexpected arguments: ${Q}. Run 'sazabi messages -h' for usage.`)}let n={token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]};if(t.limit)n.limit=Cg(t.limit,1,100,"Limit",t.json);if(t.cursor)n.cursor=t.cursor;await _nt(i,n)}).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:U("search","Search messages in the active project",async(A)=>{let{values:t,positionals:g}=S(A,{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}),i=g.join(" ");if(!i){if(t.json)return b("Search query is required. Usage: sazabi messages search <query>");return r("Search query is required. Usage: sazabi messages search <query>")}let n={token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]};if(t.limit)n.limit=Cg(t.limit,1,100,"Limit",t.json);if(t.page)n.page=Cg(t.page,1,Number.MAX_SAFE_INTEGER,"Page",t.json);if(t["thread-id"])n.threadId=t["thread-id"];if(t.role)n.role=An(t.role,["user","assistant"],"Role",t.json);await mnt(i,n)}).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();nA();aA();IA();var jO=["low","medium","high","critical"],DaA={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"}}},xnt={schema:DaA,columns:["id","notificationTypes","destinations","severities","createdAt"],header:"Notification delivery rules",emptyMessage:"No delivery rules. Create one with 'sazabi notifications delivery-rules create'."},waA={layout:"field-list",schema:DaA,fields:["id","notificationTypes","destinations","severities","components","includeDescendants","createdAt"],title:"Notification delivery rule"},_O=(A)=>({id:A.id,notificationTypes:A.notificationTypes.join(", "),destinations:A.destinations.map((t)=>t.displayName||`${t.channel}:${t.destinationKey}`).join(", "),severities:A.condition.severities?.join(", ")??null,components:A.components.length>0?A.components.map((t)=>t.label).join(", "):null,includeDescendants:A.includeDescendants,createdAt:A.createdAt}),AC={...f,"project-id":{type:"string"}},se={...R,"project-id":{type:"string",description:"Override active project ID"}},tC=(A)=>{let t=A.json,g=P({tokenFlag:A.token,projectIdFlag:A["project-id"],jsonMode:t});return{client:z({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:t}),json:t}},ZN=(A)=>{if(Array.isArray(A))return A.filter((t)=>typeof t==="string");return typeof A==="string"?[A]:[]},qnt=(A,t)=>{let g=[];for(let i of A){let n=i.indexOf(":");if(n<=0||n===i.length-1){let Q=`Invalid --destination "${i}". Use channel:key (see 'sazabi notifications delivery-rules options').`;if(t)b(Q);else r(Q);return null}g.push({channel:i.slice(0,n),destinationKey:i.slice(n+1)})}return g},dnt=(A,t)=>{for(let g of A)if(!jO.includes(g)){let i=`Invalid --severity "${g}". Allowed: ${jO.join(", ")}.`;if(t)b(i);else r(i);return null}return A},aaA={"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}},yaA={"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: ${jO.join(", ")} (repeatable)`}},raA=(A,t)=>{let g=ZN(A["notification-type"]);if(g.length===0){if(t)b("At least one --notification-type is required (see 'sazabi notifications delivery-rules options').");else r("At least one --notification-type is required (see 'sazabi notifications delivery-rules options').");return null}let i=qnt(ZN(A.destination),t);if(!i)return null;if(i.length===0){if(t)b("At least one --destination is required (see 'sazabi notifications delivery-rules options').");else r("At least one --destination is required (see 'sazabi notifications delivery-rules options').");return null}let n=dnt(ZN(A.severity),t);if(!n)return null;let Q=ZN(A["component-id"]);return{notificationTypes:g,destinations:i,includeDescendants:A["include-descendants"]===!0,condition:n.length>0?{severities:n}:{},...Q.length>0?{componentIds:Q}:{}}},pnt=async(A)=>{let{values:t}=S(A,AC),{client:g,json:i}=tC(t),{rules:n}=N(await g.notificationDeliveryRules.list(),"Couldn't list delivery rules",i);j(xnt,n.map(_O),{json:i})},mO=async(A)=>N(await A.client.notificationDeliveryRules.options(),"Couldn't load delivery rule options",A.json),xO=async(A)=>{let{client:t,json:g,...i}=A;return N(await t.notificationDeliveryRules.create(i),"Failed to create delivery rule",g)},snt=async(A)=>{let{values:t}=S(A,AC),{client:g,json:i}=tC(t),n=await mO({client:g,json:i});if(i){Z(n);return}j({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."},n.destinations,{json:!1}),j({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."},n.notificationTypes.map((Q)=>({notificationType:Q.notificationType,label:Q.label,conditions:Q.conditions.join(", ")})),{json:!1}),j({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."},n.components,{json:!1})},Ait=async(A)=>{let{values:t}=S(A,{...AC,...aaA}),{client:g,json:i}=tC(t),n=raA(t,i);if(!n)return;let Q=await xO({client:g,json:i,...n});if(i){Z(Q);return}O("Delivery rule created."),X(waA,_O(Q),{json:i})},tit=async(A)=>{let{values:t,positionals:g}=S(A,{...AC,...aaA},{allowPositionals:!0}),i=t.json,n=g[0];if(!n){if(i)return b("Delivery rule ID is required. Run 'sazabi notifications delivery-rules list' to see rule IDs.");return r("Delivery rule ID is required. Run 'sazabi notifications delivery-rules list' to see rule IDs.")}let{client:Q}=tC(t),o=raA(t,i);if(!o)return;let B=N(await Q.notificationDeliveryRules.update({...o,ruleId:n}),"Failed to update delivery rule",i);if(i){Z(B);return}O("Delivery rule updated."),X(waA,_O(B),{json:i})},git=async(A)=>{let{values:t,positionals:g}=S(A,AC,{allowPositionals:!0}),i=t.json,n=g[0];if(!n){if(i)return b("Delivery rule ID is required. Run 'sazabi notifications delivery-rules list' to see rule IDs.");return r("Delivery rule ID is required. Run 'sazabi notifications delivery-rules list' to see rule IDs.")}let{client:Q}=tC(t),o=N(await Q.notificationDeliveryRules.delete(n),"Failed to delete delivery rule",i);if(i){Z(o);return}O("Delivery rule deleted.")},nit={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"}}},iit=async(A)=>{let{values:t}=S(A,AC),{client:g,json:i}=tC(t),n=N(await g.notificationChannels.getProject(),"Couldn't load notification channels",i);if(i){Z(n);return}j({schema:nit,columns:["channel","name","scope","enabled","status"],header:`Notification channels (issue min severity: ${n.issueNotificationMinSeverity})`,emptyMessage:"No notification channels."},n.channelCards.map((Q)=>({channel:Q.channel,name:Q.name,scope:Q.scope,enabled:Q.enabled===null?"—":Q.enabled?"yes":"no",status:Q.prerequisite.statusLabel})),{json:!1})},baA=QA("notifications","Manage notification delivery rules and inspect channels").withSubcommands({"delivery-rules":U("delivery-rules","Manage project notification delivery rules").withSubcommands({list:U("list","List delivery rules",pnt).withOptions(se).withExamples(["sazabi notifications delivery-rules list # List delivery rules"]).build(),options:U("options","List available destinations, events, and conditions",snt).withOptions(se).withExamples(["sazabi notifications delivery-rules options # See what you can route"]).build(),create:U("create","Create a delivery rule",Ait).withOptions({...se,...yaA}).withExamples(["sazabi notifications delivery-rules create --notification-type issue_triggered --destination slack_channel:C0123 --severity high # Route high-severity issues to Slack"]).build(),update:U("update","Replace a delivery rule (atomic)",tit).withPositionalArgs("<rule-id>").withOptions({...se,...yaA}).withExamples(["sazabi notifications delivery-rules update <id> --notification-type issue_triggered --destination slack_channel:C0123 # Replace a rule"]).build(),delete:U("delete","Delete a delivery rule",git).withPositionalArgs("<rule-id>").withOptions(se).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:U("channels","Inspect notification channels").withSubcommands({get:U("get","List the project's notification channels",iit).withOptions(se).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();nA();IA();Ng();nA();aA();IA();Ng();var HN=new Set(["install_agent_skills"]),UaA=new Set(["install_github_app","configure_code_search","install_slack_app","configure_slack_alerts","invite_team","connect_log_sources","add_mcp_connectors","send_message"]),dO={"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"},Qit=(A,t)=>{let g=A.token?.trim()||process.env.SAZABI_TOKEN?.trim()||t.token?.trim()||"",i=A.organizationId||process.env.SAZABI_ORGANIZATION_ID?.trim()||t.activeOrganizationId||void 0,n=A.projectId||process.env.SAZABI_PROJECT_ID?.trim()||t.activeProjectId||void 0;return{token:g,organizationId:i,projectId:n}},oit=async(A,t)=>{let[g,i,n]=await Promise.all([A.tasks.list(),A.recommendations.list(),A.onboarding.getState(t?{projectId:t}:{})]);return{tasks:g.success?g.value.tasks:[],recommendations:i.success?i.value.recommendations:[],state:n.success?n.value.onboarding:null,stateError:n.success?null:n.error}},pO=async(A)=>{if(!A.projectId||!A.organizationId)return ut(void 0);let t=await A.client.projects.get(A.projectId),g=()=>wt(`The selected project (${A.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!==A.organizationId)return g();return ut(void 0)}if(t.statusCode===404||t.statusCode===403)return g();return ut(void 0)},gC=async(A)=>{let t=Boolean(A.json),g=N(oi(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t),{token:i,organizationId:n,projectId:Q}=Qit(A,g),o=z({token:i,organizationId:n,projectId:Q,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:t}),B=i?await oit(o,Q):{tasks:[],recommendations:[],state:null,stateError:null};return{client:o,profile:g,organizationId:n,projectId:Q,snapshot:B,prompts:{select:rO,multiselect:Yy,text:bO,confirm:LN},json:t}},Iit=(A,t)=>{if(!A.projectId)return!1;return XyA(A.profile,A.projectId).includes(t)},XN=async(A,t)=>{if(t.optional&&Iit(A,t.id))return{state:"skipped"};try{return await t.check(A)}catch(g){return{state:"incomplete",reason:`Couldn't check this step: ${g instanceof Error?g.message:String(g)}`}}},sO=async(A)=>{let t=[];for(let g of A.steps)t.push({step:g,status:await XN(A.ctx,g)});return t},A1=async(A)=>{let{ctx:t,stepId:g}=A;if(!t.projectId)return wt("No active project to record the skip against. Select a project first.");let i=mA();if(!i.success)return i;let n=HyA(i.value,t.projectId,g);if(!n.success)return n;let Q=at(n.value);if(!Q.success)return Q;if(g==="trigger_sample_issue")await t.client.onboarding.skipSampleIssue();return Q},Bit=(A)=>{let{statuses:t,ctx:g,webBaseUrl:i}=A,n=t.find(({step:o,status:B})=>!o.optional&&(B.state==="incomplete"||B.state==="blocked"));if(n){let{step:o,status:B}=n,h=B.state==="incomplete"?B.reason:B.state==="blocked"?`Blocked on ${B.on}`:"";return{payload:{step:o.id,reason:h,actions:o.instructions(g)},exitCode:2}}let Q=FaA(g.snapshot.state);return{payload:{step:null,reason:Q.length>0?"All required wizard steps are complete. Finish the remaining steps in the dashboard.":"All required steps are complete.",actions:Q.map((o)=>({url:`${i}/onboarding`,description:dO[o]}))},exitCode:Q.length>0?2:0}},FaA=(A)=>{if(!A||A.isCompleted)return[];return Object.entries(A.completionByStep).filter(([t,g])=>g==="incomplete"&&t!=="finish").map(([t])=>t)},NaA=async(A)=>{let t=await A.client.onboarding.getState(A.projectId?{projectId:A.projectId}:{});if(!t.success)return{outcome:"unavailable"};let g=t.value.onboarding;if(g.isCompleted)return{outcome:"already-complete"};if(g.canonicalStep==="finish"&&A.projectId){if((await A.client.onboarding.finish({projectId:A.projectId})).success)return{outcome:"finished"};return{outcome:"unavailable"}}return{outcome:"web-steps-remaining",webSteps:FaA(g)}},hit={out:(A)=>console.log(A),isInteractive:jI},WN=d.success("✓"),uaA=d.info("→"),VN=d.muted("○"),qO=d.muted("–"),LaA=async(A)=>{let{steps:t,mode:g,json:i}=A,n=A.io??hit,Q=A.webBaseUrl??zi(),o=await A.buildContext();if(i||!n.isInteractive()){let y=await sO({steps:t,ctx:o}),{payload:w,exitCode:a}=Bit({statuses:y,ctx:o,webBaseUrl:Q});if(a!==0)return Z(w),a;let u=await NaA(o);if(u.outcome==="finished"||u.outcome==="already-complete")return Z(w),0;let F=u.outcome==="web-steps-remaining"?u.webSteps:[];return Z({step:null,reason:F.length>0?"All required wizard steps are complete. Finish the remaining steps in the dashboard.":"All required wizard steps are complete, but onboarding isn't finished on the server yet.",actions:F.map((Y)=>({url:`${Q}/onboarding`,description:dO[Y]}))}),2}n.out(""),n.out(d.bold("Sazabi onboarding")),n.out("");let B=0,h=()=>{if(B>0)n.out(` ${WN} ${B} ${B===1?"step":"steps"} already complete`),B=0},e=(y)=>t.find((w)=>w.id===y)?.title??y,C=0,c=!1;for(let y of t){let w=await XN(o,y);if(w.state==="skipped"){h(),n.out(` ${qO} ${y.title} ${d.muted("(skipped)")}`);continue}if(w.state==="complete"){if(g==="start")n.out(` ${WN} ${y.title}`);else B+=1;continue}if(w.state==="blocked"){if(h(),n.out(` ${VN} ${y.title} ${d.muted(`(blocked on ${e(w.on).toLowerCase()})`)}`),!y.optional)C+=1;continue}if(h(),o=await A.buildContext(),w=await XN(o,y),w.state!=="incomplete"){if(w.state==="complete")n.out(` ${WN} ${y.title}`);else if(w.state==="skipped")n.out(` ${qO} ${y.title} ${d.muted("(skipped)")}`);else if(n.out(` ${VN} ${y.title} ${d.muted(`(blocked on ${e(w.on).toLowerCase()})`)}`),!y.optional)C+=1;continue}n.out(""),n.out(` ${uaA} ${y.title}`),n.out(` ${d.muted(w.reason)}`);let a=await o.prompts.select({message:"What next?",choices:[{label:"Configure now",value:"configure",preselected:!0},...y.optional?[{label:"Skip for now",value:"skip"}]:[],{label:"Quit and resume later",value:"quit"}]});if(a==="quit"){if(c=!0,!y.optional)C+=1;break}if(a==="skip"){let F=await A1({ctx:o,stepId:y.id});if(!F.success){n.out(` ${VN} ${y.title} ${d.warning(`(couldn't save the skip: ${F.error} — it will prompt again next run)`)}`);continue}n.out(` ${qO} ${y.title} ${d.muted("(skipped)")}`);continue}await y.run(o),o=await A.buildContext();let u=await XN(o,y);if(u.state==="complete"||u.state==="skipped")n.out(` ${WN} ${y.title}`);else if(n.out(` ${VN} ${y.title} ${d.muted("(still shows incomplete — detection can take a moment)")}`),!y.optional)C+=1}if(h(),n.out(""),c)return n.out(d.muted("Run 'sazabi onboarding' to pick up where you left off.")),0;if(C>0)return n.out(d.muted(`${C} required ${C===1?"step remains":"steps remain"} — run 'sazabi onboarding' to continue.`)),0;let E=await NaA(o);if(E.outcome==="finished"||E.outcome==="already-complete")n.out(d.success("Onboarding complete."));else if(E.outcome==="web-steps-remaining"){n.out("Remaining steps to finish in the dashboard:");for(let y of E.webSteps)n.out(` ${uaA} ${dO[y]}: ${d.info(`${Q}/onboarding`)}`)}else n.out(d.muted("All wizard steps are complete. Check 'sazabi onboarding progress' for shared state."));return 0};nA();IA();var SaA={id:"set_up_billing",title:"Billing",optional:!1,check:async(A)=>{let t=A.snapshot.state;if(!t){if(A.snapshot.stateError)return{state:"incomplete",reason:`Couldn't load the billing state (${A.snapshot.stateError}). Retry shortly.`};return{state:"blocked",on:"sign_in"}}if(t.hasPaidBillingSubscription)return{state:"complete",detectedFrom:"server"};if(!t.billingStepEnabled)return{state:"skipped"};return{state:"incomplete",reason:"No paid subscription yet. Pick a plan to subscribe."}},run:async(A)=>{let t=N(await A.client.billing.listPlans(),"Couldn't fetch plans (check your organization access and that you can manage billing)",A.json);if(t.plans.length===0){H("No self-serve plans are available. Set up billing from the dashboard.");return}let g=await A.prompts.select({message:"Choose a plan",choices:t.plans.map((i,n)=>({label:i.name,value:i.slug,hint:`${i.price} ${i.currency.toUpperCase()}`,preselected:n===0}))});await uO({client:A.client,planSlug:g,json:A.json})},instructions:()=>[{command:"sazabi billing plans list",description:"List the self-serve plans available for checkout"},{command:"sazabi billing plans subscribe --plan <slug>",description:"Subscribe via browser checkout"}]};nA();aA();import*as laA from"node:fs";import*as MaA from"node:path";var eit=(A)=>{let t=!1;for(let g of A.split(`
|
|
8768
|
+
`)},Znt=(A)=>{return A.statusCode===404};var Wnt={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:(A)=>A.threadUrl??null},runId:{label:"Run ID",type:{kind:"id"}},status:{label:"Status",type:{kind:"string"}},pollWith:{label:"Poll with",type:{kind:"string"},get:(A)=>`sazabi runs get ${A.runId}`},response:{label:"Response",type:{kind:"nullable-string"},get:(A)=>A.response}},Vnt={layout:"sections",schema:Wnt,primary:{title:"Thread",fields:["threadId","messageId","url","runId","status","pollWith"]},secondary:[{title:"Response",field:"response"}]},BaA=()=>{return process.env.SAZABI_AUTOMATION_ID??process.env.SAZABI_SCRIPT_PARAM_AUTOMATION_ID},haA=()=>process.env.SAZABI_AMBIENT_SERVICE_RUN==="true"?!0:void 0,KO=async(A)=>{let t=Date.now(),g=A.waitTimeoutSeconds===void 0?void 0:A.waitTimeoutSeconds*1000,i=await caA({message:A.message,threadId:A.threadId,projectId:A.projectId,json:A.json,client:A.client,wait:!0,timeoutMs:g,automationId:A.automationId,ambientServiceRun:A.ambientServiceRun});if(i.status==="processing"){let n=g===void 0?void 0:Math.max(0,g-(Date.now()-t)),Q=N(await vN({client:A.client,runId:i.runId,threadId:i.threadId,timeoutMs:n,printProgress:!A.json}),`Couldn't get run (poll again with 'sazabi runs get ${i.runId}')`,A.json);i={...i,status:Q.status,response:Q.response,messageId:i.messageId??Q.messageId}}return i},CaA=async(A,t={})=>{let g=P({tokenFlag:t.token,jsonMode:t.json}),i=z({token:g.token,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl}),n=t.wait?await KO({client:i,message:A,threadId:t.threadId,projectId:g.projectId,waitTimeoutSeconds:t.timeout===void 0?void 0:t.timeout/1000,json:t.json,automationId:BaA(),ambientServiceRun:haA()}):await caA({message:A,threadId:t.threadId,projectId:g.projectId,json:t.json,client:i,wait:!1,timeoutMs:t.timeout,automationId:BaA(),ambientServiceRun:haA()});X(Vnt,n,{json:t.json})},caA=async(A)=>{if(A.threadId){let g=N(await A.client.messages.append(A.threadId,A.message,A.wait??!1,eaA(A.timeoutMs),A.automationId,A.ambientServiceRun),"Failed to send message",A.json);return{threadId:A.threadId,runId:g.result.runId,messageId:g.result.messageId,status:g.result.status,response:g.result.response,threadUrl:A.projectId?Ot(A.projectId,A.threadId,void 0,g.result.messageId):void 0}}let t=N(await A.client.threads.create({message:A.message,...A.projectId?{projectId:A.projectId}:{},wait:A.wait??!1,timeoutSeconds:eaA(A.timeoutMs),...A.automationId!==void 0?{automationId:A.automationId}:{},...A.ambientServiceRun?{ambientServiceRun:!0}:{}}),"Failed to create thread",A.json);return{threadId:t.result.threadId,runId:t.result.runId,messageId:t.result.messageId,status:t.result.status,response:t.result.response,threadUrl:A.projectId?Ot(A.projectId,t.result.threadId,void 0,t.result.messageId):void 0}},eaA=(A)=>{if(A===void 0)return 20;return Math.max(1,Math.min(Math.ceil(A/1000),20))};var Xnt={id:{label:"ID",type:{kind:"string"}},role:{label:"Role",type:{kind:"role"}},content:{label:"Content",type:{kind:"custom",render:(A)=>{let g=A.find((i)=>i.type==="message"&&Boolean(i.message));return g?Pg(g.message):eg("(no text)")}}},createdAt:{label:"Created",type:{kind:"date"}}},Hnt={schema:Xnt,columns:["id","role","content","createdAt"],header:"Messages",emptyMessage:"No messages found."},Knt={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:(A)=>Pg(A)}},score:{label:"Score",align:"right",type:{kind:"custom",render:(A)=>A!=null?A.toFixed(2):"-"}}},jnt={schema:Knt,columns:["id","threadTitle","role","content","score"],header:{title:"Search results",variant:"search"},emptyMessage:"No matching messages found."},_nt=async(A,t)=>{let g=P({tokenFlag:t.token,jsonMode:t.json}),i=z({token:g.token,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl}),{messages:n,nextCursor:Q}=N(await i.messages.list(A,{limit:t.limit,cursor:t.cursor}),"Couldn't list messages (check the thread ID and try again)",t.json);j(Hnt,n,{json:t.json,nextCursor:Q})},mnt=async(A,t)=>{let g=P({tokenFlag:t.token,jsonMode:t.json}),i=z({token:g.token,projectId:g.projectId,apiBaseUrlFlag:t.apiBaseUrl}),{messages:n,pagination:Q}=N(await i.search.messages({query:A,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){Z({messages:n,pagination:Q});return}j(jnt,n,{count:Q.totalResults}),Hi({type:"page",page:Q.page,totalPages:Q.totalPages})},EaA=QA("messages","Send, list, and search messages").withSubcommands({send:U("send","Send a message (creates new thread if --thread-id omitted)",async(A)=>{let{values:t,positionals:g}=S(A,{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}),i=g.join(" ");if(!i){if(t.json)return b("Message is required. Usage: sazabi messages send <message> [--thread-id <id>]");return r("Message is required. Usage: sazabi messages send <message> [--thread-id <id>]")}let n=t.timeout?Cg(t.timeout,1,3600,"Timeout",t.json)*1000:void 0,Q={token:t.token,threadId:t["thread-id"],wait:t.wait,timeout:n,json:t.json,apiBaseUrl:t["api-base-url"]};await CaA(i,Q)}).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:U("list","List messages in a thread",async(A)=>{let{values:t,positionals:g}=S(A,{token:{type:"string"},limit:{type:"string"},cursor:{type:"string"},json:{type:"boolean"},"api-base-url":{type:"string"}},{allowPositionals:!0}),i=g[0];if(!i){if(t.json)return b("Thread ID is required. Usage: sazabi messages list <thread-id>");return r("Thread ID is required. Usage: sazabi messages list <thread-id>")}if(g.length>1){let Q=g.slice(1).join(", ");if(t.json)return b(`Unexpected arguments: ${Q}. Run 'sazabi messages -h' for usage.`);return r(`Unexpected arguments: ${Q}. Run 'sazabi messages -h' for usage.`)}let n={token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]};if(t.limit)n.limit=Cg(t.limit,1,100,"Limit",t.json);if(t.cursor)n.cursor=t.cursor;await _nt(i,n)}).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:U("search","Search messages in the active project",async(A)=>{let{values:t,positionals:g}=S(A,{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}),i=g.join(" ");if(!i){if(t.json)return b("Search query is required. Usage: sazabi messages search <query>");return r("Search query is required. Usage: sazabi messages search <query>")}let n={token:t.token,json:t.json,apiBaseUrl:t["api-base-url"]};if(t.limit)n.limit=Cg(t.limit,1,100,"Limit",t.json);if(t.page)n.page=Cg(t.page,1,Number.MAX_SAFE_INTEGER,"Page",t.json);if(t["thread-id"])n.threadId=t["thread-id"];if(t.role)n.role=An(t.role,["user","assistant"],"Role",t.json);await mnt(i,n)}).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();nA();aA();IA();var jO=["low","medium","high","critical"],DaA={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"}}},xnt={schema:DaA,columns:["id","notificationTypes","destinations","severities","createdAt"],header:"Notification delivery rules",emptyMessage:"No delivery rules. Create one with 'sazabi notifications delivery-rules create'."},waA={layout:"field-list",schema:DaA,fields:["id","notificationTypes","destinations","severities","components","includeDescendants","createdAt"],title:"Notification delivery rule"},_O=(A)=>({id:A.id,notificationTypes:A.notificationTypes.join(", "),destinations:A.destinations.map((t)=>t.displayName||`${t.channel}:${t.destinationKey}`).join(", "),severities:A.condition.severities?.join(", ")??null,components:A.components.length>0?A.components.map((t)=>t.label).join(", "):null,includeDescendants:A.includeDescendants,createdAt:A.createdAt}),AC={...f,"project-id":{type:"string"}},se={...R,"project-id":{type:"string",description:"Override active project ID"}},tC=(A)=>{let t=A.json,g=P({tokenFlag:A.token,projectIdFlag:A["project-id"],jsonMode:t});return{client:z({token:g.token,organizationId:g.organizationId,projectId:g.projectId,apiBaseUrlFlag:A["api-base-url"],jsonMode:t}),json:t}},ZN=(A)=>{if(Array.isArray(A))return A.filter((t)=>typeof t==="string");return typeof A==="string"?[A]:[]},qnt=(A,t)=>{let g=[];for(let i of A){let n=i.indexOf(":");if(n<=0||n===i.length-1){let Q=`Invalid --destination "${i}". Use channel:key (see 'sazabi notifications delivery-rules options').`;if(t)b(Q);else r(Q);return null}g.push({channel:i.slice(0,n),destinationKey:i.slice(n+1)})}return g},dnt=(A,t)=>{for(let g of A)if(!jO.includes(g)){let i=`Invalid --severity "${g}". Allowed: ${jO.join(", ")}.`;if(t)b(i);else r(i);return null}return A},aaA={"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}},yaA={"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: ${jO.join(", ")} (repeatable)`}},raA=(A,t)=>{let g=ZN(A["notification-type"]);if(g.length===0){if(t)b("At least one --notification-type is required (see 'sazabi notifications delivery-rules options').");else r("At least one --notification-type is required (see 'sazabi notifications delivery-rules options').");return null}let i=qnt(ZN(A.destination),t);if(!i)return null;if(i.length===0){if(t)b("At least one --destination is required (see 'sazabi notifications delivery-rules options').");else r("At least one --destination is required (see 'sazabi notifications delivery-rules options').");return null}let n=dnt(ZN(A.severity),t);if(!n)return null;let Q=ZN(A["component-id"]);return{notificationTypes:g,destinations:i,includeDescendants:A["include-descendants"]===!0,condition:n.length>0?{severities:n}:{},...Q.length>0?{componentIds:Q}:{}}},pnt=async(A)=>{let{values:t}=S(A,AC),{client:g,json:i}=tC(t),{rules:n}=N(await g.notificationDeliveryRules.list(),"Couldn't list delivery rules",i);j(xnt,n.map(_O),{json:i})},mO=async(A)=>N(await A.client.notificationDeliveryRules.options(),"Couldn't load delivery rule options",A.json),xO=async(A)=>{let{client:t,json:g,...i}=A;return N(await t.notificationDeliveryRules.create(i),"Failed to create delivery rule",g)},snt=async(A)=>{let{values:t}=S(A,AC),{client:g,json:i}=tC(t),n=await mO({client:g,json:i});if(i){Z(n);return}j({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."},n.destinations,{json:!1}),j({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."},n.notificationTypes.map((Q)=>({notificationType:Q.notificationType,label:Q.label,conditions:Q.conditions.join(", ")})),{json:!1}),j({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."},n.components,{json:!1})},Ait=async(A)=>{let{values:t}=S(A,{...AC,...aaA}),{client:g,json:i}=tC(t),n=raA(t,i);if(!n)return;let Q=await xO({client:g,json:i,...n});if(i){Z(Q);return}O("Delivery rule created."),X(waA,_O(Q),{json:i})},tit=async(A)=>{let{values:t,positionals:g}=S(A,{...AC,...aaA},{allowPositionals:!0}),i=t.json,n=g[0];if(!n){if(i)return b("Delivery rule ID is required. Run 'sazabi notifications delivery-rules list' to see rule IDs.");return r("Delivery rule ID is required. Run 'sazabi notifications delivery-rules list' to see rule IDs.")}let{client:Q}=tC(t),o=raA(t,i);if(!o)return;let B=N(await Q.notificationDeliveryRules.update({...o,ruleId:n}),"Failed to update delivery rule",i);if(i){Z(B);return}O("Delivery rule updated."),X(waA,_O(B),{json:i})},git=async(A)=>{let{values:t,positionals:g}=S(A,AC,{allowPositionals:!0}),i=t.json,n=g[0];if(!n){if(i)return b("Delivery rule ID is required. Run 'sazabi notifications delivery-rules list' to see rule IDs.");return r("Delivery rule ID is required. Run 'sazabi notifications delivery-rules list' to see rule IDs.")}let{client:Q}=tC(t),o=N(await Q.notificationDeliveryRules.delete(n),"Failed to delete delivery rule",i);if(i){Z(o);return}O("Delivery rule deleted.")},nit={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"}}},iit=async(A)=>{let{values:t}=S(A,AC),{client:g,json:i}=tC(t),n=N(await g.notificationChannels.getProject(),"Couldn't load notification channels",i);if(i){Z(n);return}j({schema:nit,columns:["channel","name","scope","enabled","status"],header:`Notification channels (issue min severity: ${n.issueNotificationMinSeverity})`,emptyMessage:"No notification channels."},n.channelCards.map((Q)=>({channel:Q.channel,name:Q.name,scope:Q.scope,enabled:Q.enabled===null?"—":Q.enabled?"yes":"no",status:Q.prerequisite.statusLabel})),{json:!1})},baA=QA("notifications","Manage notification delivery rules and inspect channels").withSubcommands({"delivery-rules":U("delivery-rules","Manage project notification delivery rules").withSubcommands({list:U("list","List delivery rules",pnt).withOptions(se).withExamples(["sazabi notifications delivery-rules list # List delivery rules"]).build(),options:U("options","List available destinations, events, and conditions",snt).withOptions(se).withExamples(["sazabi notifications delivery-rules options # See what you can route"]).build(),create:U("create","Create a delivery rule",Ait).withOptions({...se,...yaA}).withExamples(["sazabi notifications delivery-rules create --notification-type issue_triggered --destination slack_channel:C0123 --severity high # Route high-severity issues to Slack"]).build(),update:U("update","Replace a delivery rule (atomic)",tit).withPositionalArgs("<rule-id>").withOptions({...se,...yaA}).withExamples(["sazabi notifications delivery-rules update <id> --notification-type issue_triggered --destination slack_channel:C0123 # Replace a rule"]).build(),delete:U("delete","Delete a delivery rule",git).withPositionalArgs("<rule-id>").withOptions(se).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:U("channels","Inspect notification channels").withSubcommands({get:U("get","List the project's notification channels",iit).withOptions(se).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();nA();IA();Ng();nA();aA();IA();Ng();var HN=new Set(["install_agent_skills"]),UaA=new Set(["install_github_app","configure_code_search","install_slack_app","configure_slack_alerts","invite_team","connect_log_sources","add_mcp_connectors","send_message"]),dO={"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"},Qit=(A,t)=>{let g=A.token?.trim()||process.env.SAZABI_TOKEN?.trim()||t.token?.trim()||"",i=A.organizationId||process.env.SAZABI_ORGANIZATION_ID?.trim()||t.activeOrganizationId||void 0,n=A.projectId||process.env.SAZABI_PROJECT_ID?.trim()||t.activeProjectId||void 0;return{token:g,organizationId:i,projectId:n}},oit=async(A,t)=>{let[g,i,n]=await Promise.all([A.tasks.list(),A.recommendations.list(),A.onboarding.getState(t?{projectId:t}:{})]);return{tasks:g.success?g.value.tasks:[],recommendations:i.success?i.value.recommendations:[],state:n.success?n.value.onboarding:null,stateError:n.success?null:n.error}},pO=async(A)=>{if(!A.projectId||!A.organizationId)return ut(void 0);let t=await A.client.projects.get(A.projectId),g=()=>wt(`The selected project (${A.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!==A.organizationId)return g();return ut(void 0)}if(t.statusCode===404||t.statusCode===403)return g();return ut(void 0)},gC=async(A)=>{let t=Boolean(A.json),g=N(oi(),"Couldn't read settings (check that ~/.sazabi/settings.json is readable)",t),{token:i,organizationId:n,projectId:Q}=Qit(A,g),o=z({token:i,organizationId:n,projectId:Q,apiBaseUrlFlag:A.apiBaseUrl,jsonMode:t}),B=i?await oit(o,Q):{tasks:[],recommendations:[],state:null,stateError:null};return{client:o,profile:g,organizationId:n,projectId:Q,snapshot:B,prompts:{select:rO,multiselect:Yy,text:bO,confirm:LN},json:t}},Iit=(A,t)=>{if(!A.projectId)return!1;return XyA(A.profile,A.projectId).includes(t)},XN=async(A,t)=>{if(t.optional&&Iit(A,t.id))return{state:"skipped"};try{return await t.check(A)}catch(g){return{state:"incomplete",reason:`Couldn't check this step: ${g instanceof Error?g.message:String(g)}`}}},sO=async(A)=>{let t=[];for(let g of A.steps)t.push({step:g,status:await XN(A.ctx,g)});return t},A1=async(A)=>{let{ctx:t,stepId:g}=A;if(!t.projectId)return wt("No active project to record the skip against. Select a project first.");let i=mA();if(!i.success)return i;let n=HyA(i.value,t.projectId,g);if(!n.success)return n;let Q=at(n.value);if(!Q.success)return Q;if(g==="trigger_sample_issue")await t.client.onboarding.skipSampleIssue({projectId:t.projectId});return Q},Bit=(A)=>{let{statuses:t,ctx:g,webBaseUrl:i}=A,n=t.find(({step:o,status:B})=>!o.optional&&(B.state==="incomplete"||B.state==="blocked"));if(n){let{step:o,status:B}=n,h=B.state==="incomplete"?B.reason:B.state==="blocked"?`Blocked on ${B.on}`:"";return{payload:{step:o.id,reason:h,actions:o.instructions(g)},exitCode:2}}let Q=FaA(g.snapshot.state);return{payload:{step:null,reason:Q.length>0?"All required wizard steps are complete. Finish the remaining steps in the dashboard.":"All required steps are complete.",actions:Q.map((o)=>({url:`${i}/onboarding`,description:dO[o]}))},exitCode:Q.length>0?2:0}},FaA=(A)=>{if(!A||A.isCompleted)return[];return Object.entries(A.completionByStep).filter(([t,g])=>g==="incomplete"&&t!=="finish").map(([t])=>t)},NaA=async(A)=>{let t=await A.client.onboarding.getState(A.projectId?{projectId:A.projectId}:{});if(!t.success)return{outcome:"unavailable"};let g=t.value.onboarding;if(g.isCompleted)return{outcome:"already-complete"};if(g.canonicalStep==="finish"&&A.projectId){if((await A.client.onboarding.finish({projectId:A.projectId})).success)return{outcome:"finished"};return{outcome:"unavailable"}}return{outcome:"web-steps-remaining",webSteps:FaA(g)}},hit={out:(A)=>console.log(A),isInteractive:jI},WN=d.success("✓"),uaA=d.info("→"),VN=d.muted("○"),qO=d.muted("–"),LaA=async(A)=>{let{steps:t,mode:g,json:i}=A,n=A.io??hit,Q=A.webBaseUrl??zi(),o=await A.buildContext();if(i||!n.isInteractive()){let y=await sO({steps:t,ctx:o}),{payload:w,exitCode:a}=Bit({statuses:y,ctx:o,webBaseUrl:Q});if(a!==0)return Z(w),a;let u=await NaA(o);if(u.outcome==="finished"||u.outcome==="already-complete")return Z(w),0;let F=u.outcome==="web-steps-remaining"?u.webSteps:[];return Z({step:null,reason:F.length>0?"All required wizard steps are complete. Finish the remaining steps in the dashboard.":"All required wizard steps are complete, but onboarding isn't finished on the server yet.",actions:F.map((Y)=>({url:`${Q}/onboarding`,description:dO[Y]}))}),2}n.out(""),n.out(d.bold("Sazabi onboarding")),n.out("");let B=0,h=()=>{if(B>0)n.out(` ${WN} ${B} ${B===1?"step":"steps"} already complete`),B=0},e=(y)=>t.find((w)=>w.id===y)?.title??y,C=0,c=!1;for(let y of t){let w=await XN(o,y);if(w.state==="skipped"){h(),n.out(` ${qO} ${y.title} ${d.muted("(skipped)")}`);continue}if(w.state==="complete"){if(g==="start")n.out(` ${WN} ${y.title}`);else B+=1;continue}if(w.state==="blocked"){if(h(),n.out(` ${VN} ${y.title} ${d.muted(`(blocked on ${e(w.on).toLowerCase()})`)}`),!y.optional)C+=1;continue}if(h(),o=await A.buildContext(),w=await XN(o,y),w.state!=="incomplete"){if(w.state==="complete")n.out(` ${WN} ${y.title}`);else if(w.state==="skipped")n.out(` ${qO} ${y.title} ${d.muted("(skipped)")}`);else if(n.out(` ${VN} ${y.title} ${d.muted(`(blocked on ${e(w.on).toLowerCase()})`)}`),!y.optional)C+=1;continue}n.out(""),n.out(` ${uaA} ${y.title}`),n.out(` ${d.muted(w.reason)}`);let a=await o.prompts.select({message:"What next?",choices:[{label:"Configure now",value:"configure",preselected:!0},...y.optional?[{label:"Skip for now",value:"skip"}]:[],{label:"Quit and resume later",value:"quit"}]});if(a==="quit"){if(c=!0,!y.optional)C+=1;break}if(a==="skip"){let F=await A1({ctx:o,stepId:y.id});if(!F.success){n.out(` ${VN} ${y.title} ${d.warning(`(couldn't save the skip: ${F.error} — it will prompt again next run)`)}`);continue}n.out(` ${qO} ${y.title} ${d.muted("(skipped)")}`);continue}await y.run(o),o=await A.buildContext();let u=await XN(o,y);if(u.state==="complete"||u.state==="skipped")n.out(` ${WN} ${y.title}`);else if(n.out(` ${VN} ${y.title} ${d.muted("(still shows incomplete — detection can take a moment)")}`),!y.optional)C+=1}if(h(),n.out(""),c)return n.out(d.muted("Run 'sazabi onboarding' to pick up where you left off.")),0;if(C>0)return n.out(d.muted(`${C} required ${C===1?"step remains":"steps remain"} — run 'sazabi onboarding' to continue.`)),0;let E=await NaA(o);if(E.outcome==="finished"||E.outcome==="already-complete")n.out(d.success("Onboarding complete."));else if(E.outcome==="web-steps-remaining"){n.out("Remaining steps to finish in the dashboard:");for(let y of E.webSteps)n.out(` ${uaA} ${dO[y]}: ${d.info(`${Q}/onboarding`)}`)}else n.out(d.muted("All wizard steps are complete. Check 'sazabi onboarding progress' for shared state."));return 0};nA();IA();var SaA={id:"set_up_billing",title:"Billing",optional:!1,check:async(A)=>{let t=A.snapshot.state;if(!t){if(A.snapshot.stateError)return{state:"incomplete",reason:`Couldn't load the billing state (${A.snapshot.stateError}). Retry shortly.`};return{state:"blocked",on:"sign_in"}}if(t.hasPaidBillingSubscription)return{state:"complete",detectedFrom:"server"};if(!t.billingStepEnabled)return{state:"skipped"};return{state:"incomplete",reason:"No paid subscription yet. Pick a plan to subscribe."}},run:async(A)=>{let t=N(await A.client.billing.listPlans(),"Couldn't fetch plans (check your organization access and that you can manage billing)",A.json);if(t.plans.length===0){H("No self-serve plans are available. Set up billing from the dashboard.");return}let g=await A.prompts.select({message:"Choose a plan",choices:t.plans.map((i,n)=>({label:i.name,value:i.slug,hint:`${i.price} ${i.currency.toUpperCase()}`,preselected:n===0}))});await uO({client:A.client,planSlug:g,json:A.json})},instructions:()=>[{command:"sazabi billing plans list",description:"List the self-serve plans available for checkout"},{command:"sazabi billing plans subscribe --plan <slug>",description:"Subscribe via browser checkout"}]};nA();aA();import*as laA from"node:fs";import*as MaA from"node:path";var eit=(A)=>{let t=!1;for(let g of A.split(`
|
|
8769
8769
|
`)){let i=g.trim();if(i.startsWith("[")){t=/^\[\s*remote\s+"origin"\s*\]$/.test(i);continue}if(!t)continue;let n=i.match(/^url\s*=\s*(.+)$/);if(n?.[1])return n[1].trim()}return null},Cit=(A)=>{let t,g,i=A.match(/^[\w.-]+@([\w.-]+):(.+)$/);if(i)t=i[1],g=i[2];else try{let B=new URL(A);t=B.hostname,g=B.pathname}catch{return null}if(!t||!g)return null;let n=g.replace(/\.git$/,"").split("/").filter((B)=>B.length>0),Q=n.at(-1)??null,o=n.length>=2?n.at(-2)??null:null;return{host:t.toLowerCase(),owner:o,name:Q,fullName:o&&Q?`${o}/${Q}`:null}},xI=(A)=>{try{let t=MaA.join(A,".git","config"),g=laA.readFileSync(t,"utf-8"),i=eit(g);if(!i)return null;return Cit(i)}catch{return null}},YaA=(A)=>{if(!A)return null;if(A==="github.com"||A.endsWith(".github.com"))return"github";if(A==="bitbucket.org"||A.endsWith(".bitbucket.org"))return"bitbucket";return null};IA();Ng();var t1=(A)=>{let t=mA();if(!t.success)return!1;let g=mt(t.value);if(!g.success)return!1;let i=xt(t.value,{...A,...On(g.value)});if(!i.success)return!1;return at(i.value).success},g1=(A,t)=>{jt(`${A}, but saving it to the CLI profile failed. Run '${t}' to bind it, or re-run onboarding.`)},$aA={id:"bind_project",title:"Organization & project",optional:!1,check:async(A)=>{if(A.organizationId&&A.projectId)return{state:"complete",detectedFrom:"local"};return{state:"incomplete",reason:A.organizationId?"No active project. Create or select one to continue.":"No active organization. Create one, or accept a pending invitation."}},run:async(A)=>{let t=A.organizationId;if(!t){let e=A.snapshot.state?.pendingInvitations??[];if(e.length>0){H("You have pending invitations:");for(let w of e)H(` ${w.organizationName} — accept at ${zi()}/onboarding`)}let C=xI(process.cwd()),c=await A.prompts.text({message:"Name your organization",initial:C?.owner??void 0,placeholder:C?.owner?void 0:"e.g. Acme Corp"});if(!c){H("No organization name entered.");return}let E=N(await A.client.organizations.create(c),"Failed to create organization",A.json);if(t=E.organization.id,!t1({activeOrganizationId:E.organization.id,organizationName:E.organization.name,activeProjectId:void 0})){g1(`Organization ${E.organization.name} was created`,`sazabi organizations use ${E.organization.id}`);return}O(`Organization ${E.organization.name} created.`)}let g=await A.client.projects.list({organizationId:t}),i=g.success?g.value.projects:[],n=xI(process.cwd()),Q={kind:"create"};if(i.length>0)Q=await A.prompts.select({message:"Select a project",choices:[...i.map((e,C)=>({label:e.name,value:{kind:"existing",id:e.id},preselected:C===0})),{label:"Create a new project",value:{kind:"create"}}]});if(Q.kind==="existing"){if(t1({activeOrganizationId:t,activeProjectId:Q.id}))O("Active project set.");else g1("The project was selected",`sazabi projects use ${Q.id}`);return}let o=await A.prompts.text({message:"Name your project",initial:n?.name??void 0,placeholder:n?.name?void 0:"e.g. backend"});if(!o){H("No project name entered.");return}let B=N(await A.client.projects.create({name:o,organizationId:t}),"Failed to create project",A.json);if(t1({activeOrganizationId:t,activeProjectId:B.project.id}))O(`Project ${B.project.name} created and set active.`);else g1(`Project ${B.project.name} was created`,`sazabi projects use ${B.project.id}`)},instructions:(A)=>[...A.organizationId?[]:[{command:"sazabi organizations create --name <name>",description:"Create an organization"}],{command:"sazabi projects create --name <name>",description:"Create a project in the active organization"},{command:"sazabi projects use <project-id>",description:"Set the active project"}]};nA();var GaA=["slack","teams"],kaA=async(A)=>{let t=await A.client.integrations.listConnections();if(!t.success)return!1;return t.value.connections.some((g)=>GaA.includes(g.provider)&&g.isActive)},cit=async(A)=>{let t=await A.client.notificationDeliveryRules.list();return t.success&&t.value.rules.length>0},JaA={id:"configure_chat",title:"Chat + alerts",optional:!0,check:async(A)=>{let t=await kaA(A);if(t&&await cit(A))return{state:"complete",detectedFrom:"server"};if(!t&&A.snapshot.state?.slackSkipped)return{state:"skipped"};return{state:"incomplete",reason:t?"Chat is connected but no delivery rule routes alerts yet.":"No chat connected yet. Connect Slack or Teams to receive alerts."}},run:async(A)=>{if(!await kaA(A)){let i=await A.prompts.select({message:"Where should alerts go?",choices:GaA.map((Q,o)=>({label:Q==="slack"?"Slack":"Microsoft Teams",value:Q,preselected:o===0}))});if(!await Jy({client:A.client,provider:i,projectId:A.projectId,json:A.json}))return}let t=await mO({client:A.client,json:A.json});if(t.destinations.length===0){H("No alert destinations available yet — the connection may still be syncing channels. Re-run 'sazabi onboarding' in a moment.");return}let g=await A.prompts.select({message:"Choose an alert channel",choices:t.destinations.map((i,n)=>({label:i.displayName,value:i,hint:i.channel,preselected:n===0}))});await xO({client:A.client,json:A.json,destinations:[{channel:g.channel,destinationKey:g.destinationKey}],notificationTypes:["issue_triggered"],includeDescendants:!1,condition:{}}),O(`Alerts will be delivered to ${g.displayName}.`)},instructions:()=>[{command:"sazabi integrations connect slack",description:"Connect Slack via the browser flow"},{command:"sazabi integrations connect teams",description:"Connect Microsoft Teams via the browser flow"},{command:"sazabi notifications delivery-rules create --destination <channel:key> --notification-type issue_triggered",description:"Create the first alert delivery rule"}]};nA();IA();var So=(A,t)=>A.snapshot.tasks.some((g)=>g.id===t&&g.completed);var TaA={id:"configure_code_search",title:"Configure code search",optional:!1,check:async(A)=>{if(So(A,"configure_code_search"))return{state:"complete",detectedFrom:"server"};let t=await A.client.repos.list();if(t.success&&t.value.repos.some((g)=>g.linked))return{state:"complete",detectedFrom:"server"};return{state:"incomplete",reason:"No repositories linked yet. Link at least one so agents can search your code."}},run:async(A)=>{let t=N(await A.client.repos.list(),"Couldn't list repositories (connect a forge first and try again)",A.json),g=new Map;for(let o of t.repos)if(!o.linked&&!g.has(o.fullName))g.set(o.fullName,o);if(g.size===0){H(t.repos.length>0?"Every available repository is already linked.":"No repositories are available yet — check the forge connection.");return}let i=xI(process.cwd()),n=await A.prompts.multiselect({message:"Select the repositories to link for code search",choices:[...g.values()].map((o)=>({label:o.fullName,value:o.accessSourceId,hint:o.isPrivate?"private":"public",preselected:i?.fullName?o.fullName.toLowerCase()===i.fullName.toLowerCase():!1}))});if(n.length===0){H("Nothing selected. No repositories linked.");return}let Q=N(await A.client.repos.add({accessSourceIds:n}),"Failed to link repositories",A.json);O(`Linked ${Q.repos.length} ${Q.repos.length===1?"repository":"repositories"}.`)},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 RaA=["github","bitbucket"],PaA={id:"connect_forge",title:"Connect a forge",optional:!1,check:async(A)=>{let t=await A.client.integrations.listConnections();if(!t.success)return{state:"incomplete",reason:"No forge connected yet. Connect GitHub or Bitbucket to enable code search and pull request handling."};if(t.value.connections.some((i)=>RaA.includes(i.provider)&&i.isActive))return{state:"complete",detectedFrom:"server"};return{state:"incomplete",reason:"No forge connected yet. Connect GitHub or Bitbucket to enable code search and pull request handling."}},run:async(A)=>{let t=xI(process.cwd()),g=YaA(t?.host),i=await A.prompts.select({message:"Which forge hosts your code?",choices:RaA.map((n)=>({label:n==="github"?"GitHub":"Bitbucket",value:n,hint:n===g?"detected from your git remote":void 0,preselected:g?n===g:n==="github"}))});await Jy({client:A.client,provider:i,projectId:A.projectId,json:A.json})},instructions:()=>[{command:"sazabi integrations connect github",description:"Connect GitHub via the browser flow"},{command:"sazabi integrations connect bitbucket",description:"Connect Bitbucket via the browser flow"}]};nA();IA();var n1="__otlp__",faA="__show_all__",zaA="otel",Eit=45,yit=(A)=>{let t=A.timestamp.slice(11,19);return` ${d.muted("▸")} ${d.muted(t)} ${d.bold(A.service)} ${A.body}`},OaA=async(A)=>{if(H("Waiting for logs…"),(await ZO({client:A.client,projectId:A.projectId,durationSeconds:Eit,onEvent:(g)=>console.log(yit(g)),stopWhen:(g,i)=>i>=1,json:A.json})).logCount>0)O("Logs are flowing. Continuing…");else H("No logs yet — they'll appear once your sender starts. Continuing…")},Dit=async(A,t)=>{let g={};for(let i of t.metadataFields){let n=await A.prompts.text({message:`${t.name} ${i.name}${i.required?"":" (optional)"}`,placeholder:i.description??i.type});if(n)g[i.name]=i.type==="boolean"?n==="true":n}return g},vaA={id:"connect_log_sources",title:"Connect log sources",optional:!1,check:async(A)=>{if(So(A,"connect_log_sources"))return{state:"complete",detectedFrom:"server"};return{state:"incomplete",reason:"No log sources connected yet. Connect one to see logs flowing."}},run:async(A)=>{let t=N(await A.client.logSources.listProviders(),"Couldn't load the log source provider catalog (try again)",A.json),g=new Map(t.providers.map((o)=>[o.id,o])),i=A.snapshot.recommendations.filter((o)=>o.kind==="log_source"&&o.status==="recommended"&&g.has(o.targetId)).map((o)=>g.get(o.targetId)),n=await A.prompts.select({message:"Connect a log source",choices:[...i.map((o,B)=>({label:`${o.name} log source`,value:o.id,hint:"recommended",preselected:B===0})),{label:"OTLP exporter (any app)",value:n1,preselected:i.length===0},...i.length<t.providers.length?[{label:"Show all providers",value:faA}]:[]]});if(n===faA)n=await A.prompts.select({message:"Choose a provider",choices:[...t.providers.map((o)=>({label:o.name,value:o.id})),{label:"OTLP exporter (any app)",value:n1}]});if(n===n1){let o=await A.client.logSources.list({provider:zaA,...A.projectId?{projectId:A.projectId}:{}});if(!(o.success&&o.value.logSources.length>0))await zy({client:A.client,provider:zaA,mode:"connectionless",projectId:A.projectId,json:A.json}),O("OpenTelemetry log source created.");let h=await zO(A.client,A.json);if(!h)return;LA({"Public key":h.value}),H("Point an OTLP exporter at your Sazabi intake endpoint with this key, or pipe logs with 'sazabi logs forward -- <command>'."),jt("Store the public key securely — it is only shown once."),await OaA(A);return}let Q=g.get(n);if(!Q)return;if(Q.modes.includes("managed")){let o=await Dit(A,Q);await zy({client:A.client,provider:Q.id,metadata:o,mode:"managed",projectId:A.projectId,json:A.json}),O(`${Q.name} log source connected.`)}else{let o=await zy({client:A.client,provider:Q.id,mode:"connectionless",projectId:A.projectId,json:A.json});O(`${Q.name} log source created.`);for(let B of o.endpointCards??[])if(B.url)LA({[B.label??"Endpoint"]:B.url});if(o.publicKey)LA({"Public key":o.publicKey}),jt("Store the public key securely — it is only shown once.")}await OaA(A)},instructions:()=>[{command:"sazabi log-sources providers",description:"List the supported log source providers"},{command:"sazabi log-sources create <provider>",description:"Connect a managed log source"},{command:"sazabi logs forward -- <command>",description:"Forward logs from any process via OTLP"}]};nA();aA();var ZaA="What can you see in this project? Summarize the services that are logging, anything notable in recent logs, and what you know about the codebase so far.",WaA={id:"send_message",title:"First conversation",optional:!1,check:async(A)=>{if(So(A,"send_message"))return{state:"complete",detectedFrom:"server"};return{state:"incomplete",reason:"Ask Sazabi what it can see — the reply renders right here."}},run:async(A)=>{let t=await A.prompts.text({message:"Your first message (press enter to send the suggestion)",initial:ZaA});if(!t){H("No message entered.");return}H("Sazabi is thinking…");let g=await KO({client:A.client,message:t,projectId:A.projectId,json:A.json});if(g.response)rA("Response"),console.log(g.response);else H(`The reply is still processing — follow it with 'sazabi runs get ${g.runId}'.`);if(A.projectId)console.log(`${d.muted("Continue the conversation:")} ${d.info(Ot(A.projectId,g.threadId))}`)},instructions:()=>[{command:`sazabi messages send "${ZaA}" --wait`,description:"Send a first message and wait for the reply"}]};nA();import*as maA from"node:fs";import*as xaA from"node:os";import*as qaA from"node:path";import*as rQ from"node:path";var nC=["claude-code","codex","cursor","amp","opencode"],wit={"claude-code":{user:(A)=>rQ.join(A,".claude","skills"),project:(A)=>rQ.join(A,".claude","skills")},codex:{user:(A)=>rQ.join(A,".agents","skills"),project:(A)=>rQ.join(A,".agents","skills")},amp:{user:(A)=>rQ.join(A,".config","agents","skills"),project:(A)=>rQ.join(A,".agents","skills")},opencode:{user:(A)=>rQ.join(A,".config","opencode","skills"),project:(A)=>rQ.join(A,".opencode","skills")}},ait="Cursor does not support agent skills. Use Cursor Rules (.cursor/rules/*.mdc) instead. See https://cursor.com/docs/context/rules.",KN=(A)=>{if(A.agent==="cursor")return{kind:"unsupported",agent:"cursor",reason:ait};let t=wit[A.agent],g=A.scope==="user"?t.user(A.home):t.project(A.projectDir);return{kind:"supported",agent:A.agent,scope:A.scope,root:g}};ek();import{dirname as Uit,resolve as Fit}from"node:path";import{fileURLToPath as Lit}from"node:url";var VaA=`# Sazabi CLI Reference
|
|
8770
8770
|
|
|
8771
8771
|
The CLI is published as \`@sazabi/cli\`. Every command supports \`--json\` for machine-readable output and \`-h\` for help.
|