Skip to content

An open-source, faster Devin alternative

TypeScript
80.3 KB
Raw Blame
import { z } from 'zod'
import { apiFetch, apiFetchResponse, validate } from '@/api/client'
import { managedAgentEventSchema, type ManagedAgentEvent } from './events'
import {
  ManagedAgentEventStream,
  ManagedAgentEventStreamTimeout,
} from './live-events'
import {
  Sha256,
  ZipWriter,
  assertSinkCapacity,
  zipOverheadBytes,
  openDownloadSink,
} from './workspace-download'

const agentSchema = z.object({
  id: z.string(),
  name: z.string(),
  // Both are null until the agent has been deployed at least once.
  activeAlias: z.string().nullish(),
  activeDeploymentId: z.string().nullish(),
  deploymentCount: z.number(),
  createdAt: z.string(),
  updatedAt: z.string(),
})

// A memory resource the deployment declares (docs/agents/document-memory.mdx).
const memoryDeclarationSchema = z.object({
  id: z.string(),
  description: z.string().optional().default(''),
  provider: z
    .object({
      kind: z.string().optional().default('document'),
      maxBytes: z.number().optional(),
    })
    .optional()
    .default({ kind: 'document' }),
})

const deploymentSchema = z.object({
  id: z.string(),
  agentId: z.string(),
  alias: z.string(),
  channels: z.array(z.string()),
  connections: z.array(z.string()),
  createdAt: z.string(),
  memory: z.array(memoryDeclarationSchema).optional().default([]),
  projectDeployment: z
    .object({
      id: z.string(),
      digest: z.string(),
      localAgentId: z.string(),
      // Every agent in the project deployment, by its local id and the
      // account-level agent id the dashboard addresses it by.
      agents: z
        .array(z.object({ localId: z.string(), agentId: z.string() }))
        .optional()
        .default([]),
      resources: z.object({
        // Which agents opted into a channel's events; Project Connections
        // lists them as the channel's consumers before a connection exists.
        channelRegistrations: z
          .array(
            z.object({
              agentId: z.string(),
              channelId: z.string(),
              triggers: z.array(z.string()).optional().default([]),
            }),
          )
          .optional()
          .default([]),
        channels: z.array(
          z.object({
            id: z.string(),
            type: z.enum(['slack', 'twilio', 'email']),
            displayName: z.string().optional(),
            // Slack addresses a named conversation; the others reply on the
            // one the message arrived on, so visibility does not apply.
            destinations: z.record(
              z.string(),
              z.object({
                type: z.enum(['conversation', 'reply']),
                visibility: z.enum(['public', 'private']).optional(),
              }),
            ),
          }),
        ),
        schedules: z
          .array(
            z.object({
              id: z.string(),
              agentId: z.string(),
              cron: z.string(),
              timezone: z.string(),
              enabled: z.array(
                z.enum(['default', 'development', 'production']),
              ),
              overlap: z.enum(['skip', 'allow']),
              dispatch: z.object({
                text: z.string().optional(),
                payload: z.unknown().optional(),
              }),
            }),
          )
          .optional()
          .default([]),
      }),
    })
    .optional(),
})

const deploymentsResponseSchema = z.object({
  deployments: z.array(deploymentSchema),
})

const agentsResponseSchema = z.object({
  agents: z.array(agentSchema),
})

const managedRuntimeProfileSchema = z.object({
  customized: z.boolean(),
  displayName: z.string(),
})

const projectSchema = z.object({
  id: z.string(),
  slug: z.string(),
  name: z.string(),
  environmentMode: z.enum(['single', 'legacy']).optional().default('legacy'),
  environments: z.array(
    z.object({
      name: z.enum(['default', 'development', 'production']),
      agentId: z.string().optional(),
      activeDeploymentId: z.string().optional(),
      updatedAt: z.string(),
    }),
  ),
  agents: z.array(z.object({ id: z.string(), name: z.string() })),
  archivedAt: z.string().optional(),
  createdAt: z.string(),
  updatedAt: z.string(),
})

const projectsResponseSchema = z.object({ projects: z.array(projectSchema) })

const databaseValueSchema = z.union([z.string(), z.number(), z.null()])
const databaseResultSchema = z.object({
  columns: z.array(z.string()),
  rows: z.array(z.record(z.string(), databaseValueSchema)),
  rowsAffected: z.number(),
  truncated: z.boolean(),
})
const databaseQueryResponseSchema = z.object({
  environment: z.enum(['default', 'development', 'production']),
  result: databaseResultSchema,
})

const templateInspectionSchema = z.object({
  id: z.string(),
  repository: z.object({
    url: z.string().url(),
    fullName: z.string(),
    defaultBranch: z.literal('main'),
    commitSha: z.string().regex(/^[0-9a-f]{40}$/),
  }),
  template: z.object({
    name: z.string(),
    description: z.string(),
    documentation: z.string().url().optional(),
    defaultProjectName: z.string().optional(),
    firstRun: z.object({ agent: z.string(), prompt: z.string() }).optional(),
  }),
  agents: z.array(z.object({ id: z.string(), name: z.string() })),
  requirements: z.object({
    secrets: z.array(
      z.object({
        name: z.string(),
        description: z.string().optional(),
        documentation: z.string().url().optional(),
        required: z.boolean().default(true),
        agentId: z.string().optional(),
        allowedOrigins: z.array(z.string().url()),
      }),
    ),
    runtimeVariables: z.array(
      z.object({
        name: z.string(),
        description: z.string().optional(),
        documentation: z.string().url().optional(),
        required: z.boolean(),
        example: z.string().optional(),
        agentId: z.string().optional(),
      }),
    ),
    connections: z.array(
      z.object({
        id: z.string(),
        description: z.string().optional(),
        provider: z.string(),
        permissions: z.array(z.string()),
      }),
    ),
  }),
  expiresAt: z.string(),
})

const templateInspectionPreparingSchema = z.object({
  id: z.string(),
  status: z.literal('preparing'),
  repositoryUrl: z.string().url(),
  retryAfterMs: z.number().positive(),
})

const templateInstallationSchema = z.object({
  id: z.string(),
  inspectionId: z.string(),
  projectId: z.string(),
  projectAgentId: z.string(),
  projectUrl: z.string(),
  state: z.enum([
    'awaiting_configuration',
    'creating_project',
    'building',
    'deploying',
    'ready',
    'failed',
  ]),
  error: z.object({ stage: z.string(), message: z.string() }).optional(),
})

const secretSchema = z.object({
  name: z.string(),
  projectId: z.string(),
  environment: z.enum(['default', 'development', 'production']),
  agentId: z.string().optional(),
  allowedOrigins: z.array(z.string()),
  createdAt: z.string(),
  updatedAt: z.string(),
})

const secretsResponseSchema = z.object({ secrets: z.array(secretSchema) })

const modelAccessConnectionSchema = z.object({
  id: z.string(),
  organizationId: z.string().optional(),
  connectedByUserId: z.string().optional(),
  provider: z.enum(['anthropic', 'openai', 'openrouter', 'openai_compatible']),
  kind: z.enum([
    'claude_subscription',
    'codex_subscription',
    'openrouter_api_key',
    'openai_compatible_api',
  ]),
  label: z.string(),
  baseUrl: z.string().url().nullish(),
  externalAccountHint: z.string().nullish(),
  status: z.enum([
    'connecting',
    'connected',
    'reauth_required',
    'provider_limited',
    'plan_ineligible',
    'revoked',
    'unavailable',
  ]),
  checkedAt: z.string().nullish(),
  createdAt: z.string().nullish(),
  updatedAt: z.string().nullish(),
})

const modelAccessConnectionsResponseSchema = z.object({
  data: z.array(modelAccessConnectionSchema),
})

const modelAccessConnectResponseSchema = z.object({
  connection: modelAccessConnectionSchema,
  status: z.literal('pending'),
  authorize_url: z.string().url(),
  expires_at: z.string(),
})

const modelAccessBindingSchema = z.object({
  projectId: z.string(),
  environment: z.enum(['default', 'development', 'production']),
  provider: z.enum(['anthropic', 'openai']),
  connectionId: z.string(),
  enabled: z.boolean(),
  createdAt: z.string().nullish(),
  updatedAt: z.string().nullish(),
})

const modelAccessBindingsResponseSchema = z.object({
  data: z.array(modelAccessBindingSchema),
})

const projectModelRouteSchema = z.object({
  id: z.string(),
  projectId: z.string(),
  environment: z.enum(['default', 'development', 'production']),
  agentId: z.string().nullish(),
  connectionId: z.string(),
  model: z.string(),
  fallback: z.enum(['fail', 'managed']),
  revision: z.number(),
  createdAt: z.string().nullish(),
  updatedAt: z.string().nullish(),
})

const modelRoutesResponseSchema = z.object({
  data: z.array(projectModelRouteSchema),
})

const runtimeVariableSchema = z.object({
  name: z.string(),
  projectId: z.string(),
  environment: z.enum(['default', 'development', 'production']),
  agentId: z.string().optional(),
  createdAt: z.string(),
  updatedAt: z.string(),
})

const runtimeVariablesResponseSchema = z.object({
  variables: z.array(runtimeVariableSchema),
})

const githubInstallationSchema = z.object({
  id: z.string(),
  githubInstallationId: z.number(),
  accountLogin: z.string(),
  accountType: z.string(),
  repositorySelection: z.enum(['all', 'selected']),
  state: z.enum(['active', 'suspended', 'deleted']),
  createdAt: z.string(),
  updatedAt: z.string(),
})

const githubStatusSchema = z.object({
  environments: z.array(
    z.object({
      environment: z.enum(['default', 'development', 'production']),
      state: z.enum(['not_connected', 'active', 'suspended', 'deleted']),
      installation: githubInstallationSchema.optional(),
    }),
  ),
  connections: z.array(githubInstallationSchema),
  app: z.object({ slug: z.string() }).nullable(),
})

const githubConnectionsSchema = z.object({
  connections: z.array(githubInstallationSchema),
  app: z.object({ slug: z.string() }).nullable(),
})

const githubConnectSchema = z.object({
  installUrl: z.string().url(),
  authorizeUrl: z.string().url(),
})

const connectionSchema = z.object({
  id: z.string(),
  kind: z.enum(['tool', 'channel']),
  provider: z.string(),
  label: z.string(),
  agentId: z.string().optional().default(''),
  alias: z.string().optional().default(''),
  displayName: z.string().nullish(),
  scopes: z.array(z.string()).optional().default([]),
  status: z.string(),
  createdAt: z.string(),
  updatedAt: z.string(),
})

const projectServiceAttachmentSchema = z.object({
  projectId: z.string(),
  service: z.string(),
  provider: z.string(),
  label: z.string(),
  connectionId: z.string(),
  connection: connectionSchema,
  createdAt: z.string(),
  updatedAt: z.string(),
})

const projectServiceAttachmentsSchema = z.object({
  attachments: z.array(projectServiceAttachmentSchema),
})

const channelSchema = z.object({
  id: z.string(),
  channel: z.string(),
  channelId: z.string().optional().default('slack'),
  agentId: z.string(),
  alias: z.string(),
  appName: z.string().nullish(),
  teamName: z.string().nullish(),
  appId: z.string().nullish(),
  teamId: z.string().nullish(),
  botUserId: z.string().nullish(),
  verifiedAt: z.string().nullish(),
  verificationError: z.enum(['signing_secret_mismatch']).nullish(),
  lastEventAt: z.string().nullish(),
  status: z.string(),
  createdAt: z.string(),
  updatedAt: z.string(),
  destinations: z
    .array(
      z.object({
        name: z.string(),
        conversationId: z.string(),
        displayName: z.string(),
        verifiedAt: z.string(),
      }),
    )
    .optional()
    .default([]),
  // The agents whose registrations consume this channel in its environment.
  agents: z.array(z.string()).optional().default([]),
})

// Automated Slack setup (docs/agents/channels.mdx "Connect Slack"). The record
// is redacted by the platform: it never carries the configuration token or
// the generated app credentials, so nothing here needs to stay out of the
// query cache.
export const SLACK_SETUP_PHASES = [
  'prepared',
  'creating',
  'creation_uncertain',
  'app_created',
  'exchanging',
  'connected',
  'cancelled',
] as const
export const SLACK_SETUP_ACTIONS = [
  'create',
  'authorize',
  'manual',
  'cancel',
] as const

const slackSetupSchema = z.object({
  id: z.string(),
  requestKey: z.string(),
  projectId: z.string(),
  agentId: z.string(),
  alias: z.enum(['default', 'development', 'production']),
  channelId: z.string(),
  name: z.string(),
  connectionId: z.string(),
  phase: z.enum(SLACK_SETUP_PHASES),
  app: z.object({ id: z.string(), name: z.string() }).optional(),
  workspace: z.object({ id: z.string(), name: z.string() }).optional(),
  botUserId: z.string().optional(),
  error: z
    .object({
      code: z.string(),
      message: z.string(),
      recoverable: z.boolean(),
      retryAfterMs: z.number().optional(),
      pointer: z.string().optional(),
      at: z.string(),
    })
    .optional(),
  actions: z.array(z.enum(SLACK_SETUP_ACTIONS)),
  createdAt: z.string(),
  updatedAt: z.string(),
})

const slackSetupResponseSchema = z.object({ setup: slackSetupSchema })
const slackSetupLookupSchema = z.object({ setup: slackSetupSchema.nullable() })
const slackSetupAuthorizationSchema = z.object({
  authorizationUrl: z.string().url(),
  expiresAt: z.string(),
})

// Linear agent connections (docs/agents/linear.mdx). One per project
// environment and agent. The record never carries the app's secrets or
// tokens; its webhook URL does carry the connection's ingress token, so the
// panel shows it masked.
export const LINEAR_CONNECTION_STATUSES = [
  'pending',
  'connected',
  'revoked',
  'disconnected',
] as const
export const LINEAR_HEALTH_STATES = [
  'awaiting_credentials',
  'awaiting_authorization',
  'waiting_for_first_delegation',
  'receiving',
  'revoked',
] as const

const linearConnectionSchema = z.object({
  id: z.string(),
  projectId: z.string(),
  environment: z.enum(['default', 'development', 'production']),
  agentId: z.string(),
  name: z.string(),
  status: z.enum(LINEAR_CONNECTION_STATUSES),
  clientId: z.string().optional(),
  appUserId: z.string().optional(),
  organizationId: z.string().optional(),
  webhookUrl: z.string().url().optional(),
  createAppUrl: z.string().url().optional(),
  verifiedAt: z.string().optional(),
  verificationError: z.string().optional(),
  lastEventAt: z.string().optional(),
  teams: z
    .object({ allPublic: z.boolean(), teamIds: z.array(z.string()) })
    .optional(),
  health: z
    .object({
      state: z.enum(LINEAR_HEALTH_STATES),
      message: z.string(),
      lastEventAt: z.string().optional(),
    })
    .optional(),
  revision: z.number(),
  createdAt: z.string(),
  updatedAt: z.string(),
})
const linearConnectionResponseSchema = z.object({
  connection: linearConnectionSchema,
})
const linearConnectionsResponseSchema = z.object({
  connections: z.array(linearConnectionSchema),
})
const linearCreateResponseSchema = z.object({
  connectionId: z.string(),
  webhookUrl: z.string().url(),
  createAppUrl: z.string().url(),
  connection: linearConnectionSchema,
})
const linearAuthorizeResponseSchema = z.object({
  authorizeUrl: z.string().url(),
  expiresAt: z.string(),
})
const linearDisconnectResponseSchema = z.object({
  connection: linearConnectionSchema,
  revoked: z.boolean(),
})

const connectionsResponseSchema = z.object({
  connections: z.array(connectionSchema),
})

const channelIdentityLinkSchema = z.object({ linked: z.literal(true) })

const connectionLinkSchema = z.object({
  connectionId: z.string(),
  service: z.string(),
  label: z.string(),
  status: z.enum(['connected', 'pending']),
  authorizationUrl: z.string().url().optional(),
})

const connectionStatusSchema = z.object({
  connectionId: z.string(),
  service: z.string(),
  label: z.string(),
  status: z.enum(['connected', 'pending']),
})

const connectionDisconnectSchema = z.object({
  connectionId: z.string(),
  service: z.string(),
  label: z.string(),
  status: z.string(),
})

const channelsResponseSchema = z.object({
  channels: z.array(channelSchema),
})

const scheduleSchema = z.object({
  id: z.string(),
  projectId: z.string(),
  environment: z.enum(['default', 'development', 'production']),
  agentId: z.string(),
  deploymentId: z.string(),
  cron: z.string(),
  timezone: z.string(),
  overlap: z.enum(['skip', 'allow']),
  dispatch: z.object({
    text: z.string().optional(),
    payload: z.unknown().optional(),
  }),
  nextRunAt: z.string(),
  lastRunAt: z.string().optional(),
  status: z.enum(['active', 'manual', 'paused']),
})

const scheduleRunSchema = z.object({
  id: z.string(),
  scheduleId: z.string(),
  projectId: z.string(),
  environment: z.enum(['default', 'development', 'production']),
  deploymentId: z.string(),
  scheduledAt: z.string(),
  manual: z.boolean(),
  attempt: z.number(),
  outcome: z.enum(['pending', 'enacted', 'skipped', 'failed']),
  sessionId: z.string().optional(),
  error: z.string().optional(),
  createdAt: z.string(),
})

const schedulesResponseSchema = z.object({ schedules: z.array(scheduleSchema) })
const scheduleRunsResponseSchema = z.object({
  runs: z.array(scheduleRunSchema),
})
const scheduleRunResponseSchema = z.object({ run: scheduleRunSchema })

const webhookSchema = z.object({
  id: z.string(),
  projectId: z.string(),
  environment: z.enum(['default', 'development', 'production']),
  agentId: z.string(),
  name: z.string(),
  enabled: z.boolean(),
  identity: z.string().optional(),
  invocationUrl: z.string().url(),
  token: z.string().optional(),
  createdAt: z.string(),
  updatedAt: z.string(),
  lastInvokedAt: z.string().optional(),
})

const webhooksResponseSchema = z.object({ webhooks: z.array(webhookSchema) })
const webhookResponseSchema = z.object({ webhook: webhookSchema })

const slackManifestResponseSchema = z.object({
  connection: channelSchema,
  manifest: z.record(z.string(), z.unknown()),
  createUrl: z.string().url(),
  steps: z.array(z.string()),
})

const sessionCreateSchema = z.object({
  session: z.object({
    id: z.string(),
    executionMode: z.enum(['microvm', 'workerd']).optional().default('microvm'),
  }),
  deployment: deploymentSchema.optional(),
})

const eventSchema = managedAgentEventSchema

const renderDebugSchema = z.object({
  renderId: z.string(),
  responseId: z.string(),
  providerTurn: z.number(),
  stateVersion: z.number(),
  instructionsHash: z.string(),
  instructions: z.string(),
  enabledTools: z.array(z.string()),
  enabledSubagents: z.array(z.string()).optional(),
  requiredConnections: z.array(z.string()),
  enabledMcpServers: z.array(z.string()),
  input: z.object({ source: z.string(), text: z.string().optional() }),
  tools: z.array(z.object({ name: z.string(), description: z.string() })),
  model: z.object({ provider: z.string(), model: z.string() }).optional(),
  renderedAt: z.string(),
})

const modelRouteSchema = z.object({
  requested: z
    .object({ provider: z.string(), model: z.string() })
    .nullable()
    .optional(),
  effective: z
    .object({ provider: z.string(), model: z.string() })
    .nullable()
    .optional(),
  runtime: z.string(),
  access: z.object({
    type: z.enum(['managed', 'external_subscription', 'external_api_key']),
    connectionId: z.string().optional(),
    connectionKind: z.string().optional(),
  }),
  source: z
    .enum(['agent_route', 'project_route', 'use_model', 'platform_default'])
    .optional(),
  routeId: z.string().optional(),
  routeRevision: z.number().optional(),
  fallback: z.enum(['fail', 'managed']).optional(),
  openComputerModelChargeUsd: z.number().nullable(),
})

const eventsResponseSchema = z.object({
  events: z.array(eventSchema),
})

const turnSchema = z.object({
  turnId: z.string(),
  status: z.string(),
  duplicate: z.boolean(),
})

export type ManagedAgentInputMode = 'queue' | 'steer' | 'interrupt'

const sessionSchema = z.object({
  id: z.string(),
  agentId: z.string(),
  deploymentId: z.string(),
  executionMode: z.enum(['microvm', 'workerd']).optional().default('microvm'),
  status: z.string(),
  source: z
    .enum(['api', 'channel', 'playground', 'schedule', 'webhook'])
    .optional()
    .default('api'),
  microvmState: z.string().optional(),
  createdAt: z.string(),
  updatedAt: z.string(),
  turns: z
    .array(
      z.object({
        id: z.string(),
        input: z.string(),
        mode: z
          .enum(['queue', 'steer', 'interrupt'])
          .optional()
          .default('queue'),
        status: z.string(),
        createdAt: z.string(),
        updatedAt: z.string(),
      }),
    )
    .default([]),
  // Memory bindings fixed at session creation; `writable` is false once the
  // session ended or while the document's agent writes are disabled.
  memory: z
    .array(
      z.object({
        resource: z.string(),
        scope: z.enum(['document', 'collection']),
        id: z.string().optional(),
        access: z.enum(['read', 'read-write']),
        writable: z.boolean(),
      }),
    )
    .optional()
    .default([]),
})

// One list row (docs/agents/api.mdx, "Get and list"): no turns and no memory;
// the session route keeps those. `activity` summarizes the turn work and
// `result` is the agent's latest committed result tool output, when any.
const sessionSummarySchema = z.object({
  id: z.string(),
  projectId: z.string(),
  agentId: z.string(),
  deploymentId: z.string(),
  environment: z
    .enum(['default', 'development', 'production'])
    .nullable()
    .default(null),
  source: z
    .enum(['api', 'channel', 'playground', 'schedule', 'webhook'])
    .optional()
    .default('api'),
  status: z.string(),
  labels: z.record(z.string(), z.string()).default({}),
  createdAt: z.string(),
  updatedAt: z.string(),
  revision: z.number(),
  activity: z
    .object({
      activeTurnId: z.string().nullable().default(null),
      queued: z.number().default(0),
      lastSettledTurn: z
        .object({ id: z.string(), status: z.string(), at: z.string() })
        .nullable()
        .default(null),
    })
    .default({ activeTurnId: null, queued: 0, lastSettledTurn: null }),
  result: z
    .object({
      turnId: z.string(),
      callId: z.string(),
      reportedAt: z.string(),
      data: z.unknown(),
    })
    .nullable()
    .default(null),
})

const sessionsResponseSchema = z.object({
  sessions: z.array(sessionSummarySchema),
  nextCursor: z.string().nullable().default(null),
})

// Project memory documents (docs/agents/document-memory.mdx, "Management API").
const memoryWriterSchema = z.union([
  z.object({ kind: z.literal('owner') }),
  z.object({ kind: z.literal('agent'), sessionId: z.string() }),
])

const memoryDocumentMetaSchema = z.object({
  id: z.string(),
  title: z.string(),
  summary: z.string(),
  agentWrites: z.enum(['enabled', 'disabled']),
  revision: z.string(),
  bytes: z.number(),
  maxBytes: z.number(),
  updatedAt: z.string(),
  writer: memoryWriterSchema,
})

const memoryDocumentSchema = memoryDocumentMetaSchema.extend({
  text: z.string(),
})

const memoryDocumentPageSchema = z.object({
  documents: z.array(memoryDocumentMetaSchema),
  nextCursor: z.string().nullable(),
})

// The environment's durable resource inventory. Storage outlives code, so a
// resource stays listed while it holds documents after every deployment
// stopped declaring it (`declared: false`).
const memoryResourceSchema = z.object({
  id: z.string(),
  provider: z
    .object({
      kind: z.string().optional().default('document'),
      maxBytes: z.number().optional(),
    })
    .optional()
    .default({ kind: 'document' }),
  declared: z.boolean(),
  documents: z.number(),
})

const memoryResourceInventorySchema = z.object({
  resources: z.array(memoryResourceSchema),
})

const projectOverviewSchema = z.object({
  project: projectSchema,
  templateSource: z
    .object({
      repositoryUrl: z.string().url(),
      commitSha: z.string().regex(/^[0-9a-f]{40}$/),
      cloneReady: z.boolean().optional().default(false),
    })
    .optional(),
  sessions: z.array(sessionSummarySchema),
  deployments: z.array(deploymentSchema),
  connections: z.array(connectionSchema),
  channels: z.array(channelSchema),
  schedules: z.array(z.record(z.string(), z.unknown())),
  schema: z.record(z.string(), z.unknown()),
})

export type ManagedAgentSummary = z.infer<typeof agentSchema>
export type ManagedRuntimeProfile = z.infer<typeof managedRuntimeProfileSchema>
export type ManagedProject = z.infer<typeof projectSchema>
export type ManagedProjectOverview = z.infer<typeof projectOverviewSchema>
export type ManagedAgentDeployment = z.infer<typeof deploymentSchema>
export type { ManagedAgentEvent } from './events'
export type ManagedAgentRenderDebug = z.infer<typeof renderDebugSchema>
export type ManagedAgentModelRoute = z.infer<typeof modelRouteSchema>
export type ManagedAgentSession = z.infer<typeof sessionSchema>
export type ManagedAgentSessionSummary = z.infer<typeof sessionSummarySchema>
export type ManagedSessionMemoryBinding = ManagedAgentSession['memory'][number]
export type ManagedMemoryDeclaration = z.infer<typeof memoryDeclarationSchema>
export type ManagedMemoryDocumentMeta = z.infer<typeof memoryDocumentMetaSchema>
export type ManagedMemoryDocument = z.infer<typeof memoryDocumentSchema>
export type ManagedMemoryDocumentPage = z.infer<typeof memoryDocumentPageSchema>
export type ManagedMemoryResource = z.infer<typeof memoryResourceSchema>
/** A document with the ETag the next conditional request must send back verbatim. */
export type ManagedMemoryDocumentRead = {
  document: ManagedMemoryDocument
  etag: string
}
export type ManagedAgentConnection = z.infer<typeof connectionSchema>
export type ManagedProjectServiceAttachment = z.infer<
  typeof projectServiceAttachmentSchema
>
export type ManagedAgentChannel = z.infer<typeof channelSchema>
export type ManagedAgentSchedule = z.infer<typeof scheduleSchema>
export type ManagedAgentScheduleRun = z.infer<typeof scheduleRunSchema>
export type ManagedAgentWebhook = z.infer<typeof webhookSchema>
export type ManagedSlackManifest = z.infer<typeof slackManifestResponseSchema>
export type ManagedSlackSetup = z.infer<typeof slackSetupSchema>
export type ManagedSlackSetupPhase = ManagedSlackSetup['phase']
export type ManagedSlackSetupAction = ManagedSlackSetup['actions'][number]
export type ManagedLinearConnection = z.infer<typeof linearConnectionSchema>
export type ManagedLinearHealthState = (typeof LINEAR_HEALTH_STATES)[number]
export type ManagedProjectSecret = z.infer<typeof secretSchema>
export type ManagedModelAccessConnection = z.infer<
  typeof modelAccessConnectionSchema
>
export type ManagedModelAccessBinding = z.infer<typeof modelAccessBindingSchema>
export type ManagedProjectModelRoute = z.infer<typeof projectModelRouteSchema>
export type TemplateInspection = z.infer<typeof templateInspectionSchema>
export type TemplateInstallation = z.infer<typeof templateInstallationSchema>

const UUID_NAME =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i

export function displayManagedAgentName(
  agent: Pick<ManagedAgentSummary, 'id' | 'name'>,
) {
  const name = agent.name.trim()
  return !name || UUID_NAME.test(name) ? 'Untitled agent' : name
}

export async function getManagedAgents() {
  return (
    await apiFetch('/managed-agents/agents', undefined, agentsResponseSchema)
  ).agents
}

export async function getManagedRuntimeProfile() {
  return apiFetch(
    '/managed-agents/account/runtime-profile',
    undefined,
    managedRuntimeProfileSchema,
  )
}

export async function getManagedProjects(options: { archived?: boolean } = {}) {
  return (
    await apiFetch(
      `/managed-agents/projects${options.archived ? '?archived=true' : ''}`,
      undefined,
      projectsResponseSchema,
    )
  ).projects
}

export async function createManagedProject(name: string) {
  return apiFetch(
    '/managed-agents/projects',
    { method: 'POST', body: JSON.stringify({ name }) },
    projectSchema,
  )
}

export async function archiveManagedProject(projectId: string) {
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(projectId)}/archive`,
    { method: 'POST' },
    projectSchema,
  )
}

export async function restoreManagedProject(projectId: string) {
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(projectId)}/restore`,
    { method: 'POST' },
    projectSchema,
  )
}

export async function inspectManagedTemplate(
  repositoryUrl: string,
): Promise<z.infer<typeof templateInspectionSchema>> {
  const deadline = Date.now() + 10 * 60_000
  for (;;) {
    const result = await apiFetch(
      '/managed-agents/template-inspections',
      { method: 'POST', body: JSON.stringify({ repositoryUrl }) },
      z.union([templateInspectionSchema, templateInspectionPreparingSchema]),
    )
    if ((result as { status?: string }).status !== 'preparing') {
      return result as z.infer<typeof templateInspectionSchema>
    }
    const preparing = result as z.infer<
      typeof templateInspectionPreparingSchema
    >
    if (Date.now() >= deadline) {
      throw new Error(
        'Template preparation is still running; try again shortly',
      )
    }
    await new Promise((resolve) =>
      setTimeout(resolve, Math.max(500, preparing.retryAfterMs)),
    )
  }
}

export async function createManagedTemplateInstallation(input: {
  inspectionId: string
  projectName: string
  idempotencyKey: string
}) {
  return apiFetch(
    '/managed-agents/template-installations',
    { method: 'POST', body: JSON.stringify(input) },
    templateInstallationSchema,
  )
}

export async function finalizeManagedTemplateInstallation(id: string) {
  return apiFetch(
    `/managed-agents/template-installations/${encodeURIComponent(id)}/finalize`,
    { method: 'POST' },
    templateInstallationSchema,
  )
}

export async function getManagedTemplateInstallation(id: string) {
  return apiFetch(
    `/managed-agents/template-installations/${encodeURIComponent(id)}`,
    undefined,
    templateInstallationSchema,
  )
}

export async function getManagedProject(projectId: string) {
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(projectId)}`,
    undefined,
    projectOverviewSchema,
  )
}

export type ManagedDatabaseValue = z.infer<typeof databaseValueSchema>
export type ManagedDatabaseResult = z.infer<typeof databaseResultSchema>

export async function queryManagedProjectDatabase(input: {
  projectId: string
  environment: 'default' | 'development' | 'production'
  sql: string
  parameters?: Array<string | number | boolean | null>
}) {
  return (
    await apiFetch(
      `/managed-agents/projects/${encodeURIComponent(input.projectId)}/database/query`,
      {
        method: 'POST',
        body: JSON.stringify({
          environment: input.environment,
          sql: input.sql,
          parameters: input.parameters ?? [],
        }),
      },
      databaseQueryResponseSchema,
    )
  ).result
}

export async function getManagedGitHubStatus(projectId: string) {
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(projectId)}/github`,
    undefined,
    githubStatusSchema,
  )
}

export async function connectManagedGitHub(input: {
  projectId: string
  environments: Array<'default' | 'development' | 'production'>
}) {
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/github/connect`,
    {
      method: 'POST',
      body: JSON.stringify({ environments: input.environments }),
    },
    githubConnectSchema,
  )
}

export async function getManagedGitHubConnections() {
  return apiFetch('/managed-agents/github', undefined, githubConnectionsSchema)
}

export async function addManagedGitHubConnection(mode: 'install' | 'existing') {
  const result = await apiFetch(
    '/managed-agents/github/connect',
    { method: 'POST', body: '{}' },
    githubConnectSchema,
  )
  return mode === 'existing' ? result.authorizeUrl : result.installUrl
}

export async function attachManagedGitHub(input: {
  projectId: string
  environment: 'default' | 'development' | 'production'
  connectionId: string
}) {
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/github/attach`,
    {
      method: 'POST',
      body: JSON.stringify({
        environment: input.environment,
        connectionId: input.connectionId,
      }),
    },
    z.object({ attached: z.boolean() }),
  )
}

export async function disconnectManagedGitHub(input: {
  projectId: string
  environment: 'default' | 'development' | 'production'
}) {
  return apiFetch<void>(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/github?environment=${input.environment}`,
    { method: 'DELETE' },
  )
}

const deploymentSourceSchema = z.object({
  projectId: z.string(),
  connectionId: z.string(),
  repository: z.object({
    id: z.number(),
    fullName: z.string(),
    url: z.string(),
  }),
  branch: z.string(),
  path: z.string().nullable(),
  previewsEnabled: z.boolean(),
  connection: z
    .object({
      id: z.string(),
      accountLogin: z.string(),
      state: z.enum(['active', 'suspended', 'deleted']),
    })
    .nullable(),
  createdAt: z.string(),
  updatedAt: z.string(),
})

const gitBuildSchema = z.object({
  id: z.string(),
  projectId: z.string(),
  kind: z.enum(['branch', 'preview']),
  alias: z.string(),
  ref: z.string(),
  commitSha: z.string(),
  pullRequest: z
    .object({ number: z.number(), title: z.string(), url: z.string() })
    .optional(),
  state: z.enum(['queued', 'building', 'ready', 'failed', 'removed']),
  error: z.string().optional(),
  previewUrl: z.string().optional(),
  createdAt: z.string(),
  updatedAt: z.string(),
})

const deploymentSourceStatusSchema = z.object({
  source: deploymentSourceSchema.nullable(),
  builds: z.array(gitBuildSchema),
  previews: z.array(gitBuildSchema),
})

export type ManagedDeploymentSource = z.infer<typeof deploymentSourceSchema>
export type ManagedGitBuild = z.infer<typeof gitBuildSchema>
export type ManagedDeploymentSourceStatus = z.infer<
  typeof deploymentSourceStatusSchema
>

export async function getManagedDeploymentSource(projectId: string) {
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(projectId)}/deployment-source`,
    undefined,
    deploymentSourceStatusSchema,
  )
}

export async function setManagedDeploymentSource(input: {
  projectId: string
  connectionId: string
  repository: { id: number; fullName: string }
  branch: string
  path?: string | null
  previewsEnabled: boolean
}) {
  const { projectId, ...body } = input
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(projectId)}/deployment-source`,
    { method: 'PUT', body: JSON.stringify(body) },
    deploymentSourceStatusSchema,
  )
}

export async function removeManagedDeploymentSource(projectId: string) {
  return apiFetch<void>(
    `/managed-agents/projects/${encodeURIComponent(projectId)}/deployment-source`,
    { method: 'DELETE' },
  )
}

export async function deployManagedDeploymentSource(projectId: string) {
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(projectId)}/deployment-source/deploy`,
    { method: 'POST' },
    z.object({ build: gitBuildSchema }),
  )
}

export async function removeManagedPreview(input: {
  projectId: string
  alias: string
}) {
  return apiFetch<void>(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/deployment-source/previews/${encodeURIComponent(input.alias)}`,
    { method: 'DELETE' },
  )
}

const deploymentSourceRepositoriesSchema = z.object({
  repositories: z.array(
    z.object({
      id: z.number(),
      fullName: z.string(),
      private: z.boolean(),
      defaultBranch: z.string(),
      archived: z.boolean(),
    }),
  ),
  nextCursor: z.string().nullable(),
})

export type ManagedDeploymentSourceRepository = z.infer<
  typeof deploymentSourceRepositoriesSchema
>['repositories'][number]

export async function listManagedDeploymentSourceRepositories(input: {
  projectId: string
  connectionId: string
  cursor?: string | null
}) {
  const query = new URLSearchParams({ connectionId: input.connectionId })
  if (input.cursor) query.set('cursor', input.cursor)
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/deployment-source/repositories?${query.toString()}`,
    undefined,
    deploymentSourceRepositoriesSchema,
  )
}

export async function listManagedDeploymentSourceBranches(input: {
  projectId: string
  connectionId: string
  repository: string
}) {
  const query = new URLSearchParams({
    connectionId: input.connectionId,
    repository: input.repository,
  })
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/deployment-source/branches?${query.toString()}`,
    undefined,
    z.object({
      branches: z.array(z.object({ name: z.string(), commitSha: z.string() })),
    }),
  )
}

export async function getManagedModelAccessConnections() {
  return (
    await apiFetch(
      '/managed-agents/model-access/connections',
      undefined,
      modelAccessConnectionsResponseSchema,
    )
  ).data
}

export async function connectManagedModelAccess() {
  return apiFetch(
    '/managed-agents/model-access/connections',
    { method: 'POST', body: JSON.stringify({ provider: 'openai' }) },
    modelAccessConnectResponseSchema,
  )
}

export async function connectManagedModelApiKey(input: {
  provider: 'openrouter' | 'openai_compatible'
  apiKey: string
  baseUrl?: string
  label?: string
}) {
  return apiFetch(
    '/managed-agents/model-access/connections',
    {
      method: 'POST',
      body: JSON.stringify({
        provider: input.provider,
        api_key: input.apiKey,
        base_url: input.baseUrl,
        label: input.label,
      }),
    },
    modelAccessConnectionSchema,
  )
}

export async function connectManagedClaudeSetupToken(token: string) {
  return apiFetch(
    '/managed-agents/model-access/connections',
    {
      method: 'POST',
      body: JSON.stringify({ provider: 'anthropic', token }),
    },
    modelAccessConnectionSchema,
  )
}

export async function getManagedModelRoutes(projectId: string) {
  return (
    await apiFetch(
      `/managed-agents/projects/${encodeURIComponent(projectId)}/model-routes`,
      undefined,
      modelRoutesResponseSchema,
    )
  ).data
}

export async function putManagedModelRoute(input: {
  projectId: string
  environment: 'default' | 'development' | 'production'
  connectionId: string
  model: string
  fallback: 'fail' | 'managed'
  agentId?: string
}) {
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/model-routes/${input.environment}`,
    {
      method: 'PUT',
      body: JSON.stringify({
        connection_id: input.connectionId,
        model: input.model,
        fallback: input.fallback,
        agent_id: input.agentId,
      }),
    },
    projectModelRouteSchema,
  )
}

export async function deleteManagedModelRoute(input: {
  projectId: string
  environment: 'default' | 'development' | 'production'
  agentId?: string
}) {
  return apiFetch<void>(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/model-routes/${input.environment}`,
    {
      method: 'DELETE',
      body: JSON.stringify(input.agentId ? { agent_id: input.agentId } : {}),
    },
  )
}

export async function completeManagedModelAccess(
  id: string,
  code: string,
  state: string,
) {
  return apiFetch(
    `/managed-agents/model-access/connections/${encodeURIComponent(id)}/complete`,
    { method: 'POST', body: JSON.stringify({ code, state }) },
    modelAccessConnectionSchema,
  )
}

export async function validateManagedModelAccessConnection(id: string) {
  return apiFetch(
    `/managed-agents/model-access/connections/${encodeURIComponent(id)}/validate`,
    { method: 'POST' },
    modelAccessConnectionSchema,
  )
}

export async function disconnectManagedModelAccessConnection(id: string) {
  return apiFetch(
    `/managed-agents/model-access/connections/${encodeURIComponent(id)}`,
    { method: 'DELETE' },
    modelAccessConnectionSchema,
  )
}

export async function getManagedModelAccessBindings(projectId: string) {
  return (
    await apiFetch(
      `/managed-agents/projects/${encodeURIComponent(projectId)}/model-access/bindings`,
      undefined,
      modelAccessBindingsResponseSchema,
    )
  ).data
}

export async function putManagedModelAccessBinding(input: {
  projectId: string
  provider: 'anthropic' | 'openai'
  environment: 'default' | 'development' | 'production'
  enabled: boolean
}) {
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/model-access/bindings/${input.provider}/${input.environment}`,
    { method: 'PUT', body: JSON.stringify({ enabled: input.enabled }) },
    modelAccessBindingSchema,
  )
}

export async function getManagedProjectSecrets(
  projectId: string,
  environment: 'default' | 'development' | 'production',
) {
  return (
    await apiFetch(
      `/managed-agents/projects/${encodeURIComponent(projectId)}/secrets?environment=${encodeURIComponent(environment)}`,
      undefined,
      secretsResponseSchema,
    )
  ).secrets
}

export async function putManagedProjectSecret(input: {
  projectId: string
  environment: 'default' | 'development' | 'production'
  agentId?: string
  name: string
  value: string
  allowedOrigins: string[]
}) {
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/secrets/${encodeURIComponent(input.name)}`,
    {
      method: 'PUT',
      body: JSON.stringify({
        environment: input.environment,
        ...(input.agentId ? { agentId: input.agentId } : {}),
        value: input.value,
        allowedOrigins: input.allowedOrigins,
      }),
    },
    secretSchema,
  )
}

export async function deleteManagedProjectSecret(input: {
  projectId: string
  environment: 'default' | 'development' | 'production'
  agentId?: string
  name: string
}) {
  const query = new URLSearchParams({ environment: input.environment })
  if (input.agentId) query.set('agentId', input.agentId)
  return apiFetch<void>(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/secrets/${encodeURIComponent(input.name)}?${query.toString()}`,
    { method: 'DELETE' },
  )
}

export async function getAgentRuntimeVariables(
  projectId: string,
  environment: 'default' | 'development' | 'production',
) {
  return (
    await apiFetch(
      `/managed-agents/projects/${encodeURIComponent(projectId)}/runtime-variables?environment=${encodeURIComponent(environment)}`,
      undefined,
      runtimeVariablesResponseSchema,
    )
  ).variables
}

export async function putAgentRuntimeVariable(input: {
  projectId: string
  environment: 'default' | 'development' | 'production'
  agentId?: string
  name: string
  value: string
}) {
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/runtime-variables/${encodeURIComponent(input.name)}`,
    {
      method: 'PUT',
      body: JSON.stringify({
        environment: input.environment,
        ...(input.agentId ? { agentId: input.agentId } : {}),
        value: input.value,
      }),
    },
    runtimeVariableSchema,
  )
}

export async function deleteAgentRuntimeVariable(input: {
  projectId: string
  environment: 'default' | 'development' | 'production'
  agentId?: string
  name: string
}) {
  const query = new URLSearchParams({ environment: input.environment })
  if (input.agentId) query.set('agentId', input.agentId)
  return apiFetch<void>(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/runtime-variables/${encodeURIComponent(input.name)}?${query.toString()}`,
    { method: 'DELETE' },
  )
}

export async function getManagedAgentConnections() {
  return (
    await apiFetch(
      '/managed-agents/connections',
      undefined,
      connectionsResponseSchema,
    )
  ).connections.filter((connection) => connection.kind === 'tool')
}

export async function listManagedProjectServiceConnections(projectId: string) {
  return (
    await apiFetch(
      `/managed-agents/projects/${encodeURIComponent(projectId)}/service-connections`,
      undefined,
      projectServiceAttachmentsSchema,
    )
  ).attachments
}

export async function attachManagedProjectServiceConnection(input: {
  projectId: string
  connectionId: string
}) {
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/service-connections`,
    {
      method: 'POST',
      body: JSON.stringify({ connectionId: input.connectionId }),
    },
    projectServiceAttachmentSchema,
  )
}

export async function detachManagedProjectServiceConnection(input: {
  projectId: string
  connectionId: string
}) {
  return apiFetch<void>(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/service-connections`,
    {
      method: 'DELETE',
      body: JSON.stringify({ connectionId: input.connectionId }),
    },
  )
}

export async function claimManagedAgentChannelIdentity(token: string) {
  return apiFetch(
    '/managed-agents/connections/channel-identity/link',
    {
      method: 'POST',
      body: JSON.stringify({ token }),
    },
    channelIdentityLinkSchema,
  )
}

export async function linkManagedAgentConnection(
  service: string,
  label: string,
) {
  return apiFetch(
    '/managed-agents/connections/link',
    {
      method: 'POST',
      body: JSON.stringify({ service, label }),
    },
    connectionLinkSchema,
  )
}

export async function refreshManagedAgentConnection(
  provider: 'google' | 'github' | 'linear',
  service: string,
  connectionId: string,
) {
  const query = new URLSearchParams({ service, connectionId })
  return apiFetch(
    `/managed-agents/connections/${provider}/status?${query.toString()}`,
    undefined,
    connectionStatusSchema,
  )
}

export async function disconnectManagedAgentConnection(
  provider: 'google' | 'github' | 'linear',
  service: string,
  connectionId: string,
) {
  const query = new URLSearchParams({ service, connectionId })
  return apiFetch(
    `/managed-agents/connections/${provider}?${query.toString()}`,
    { method: 'DELETE' },
    connectionDisconnectSchema,
  )
}

export async function getManagedAgentChannels() {
  return (
    await apiFetch(
      '/managed-agents/channels',
      undefined,
      channelsResponseSchema,
    )
  ).channels
}

export async function getManagedAgentSchedules(
  projectId: string,
  agentId: string,
  environment: 'default' | 'development' | 'production',
) {
  const query = new URLSearchParams({ projectId, agentId, environment })
  return (
    await apiFetch(
      `/managed-agents/schedules?${query.toString()}`,
      undefined,
      schedulesResponseSchema,
    )
  ).schedules
}

export async function getManagedAgentScheduleRuns(
  projectId: string,
  agentId: string,
  environment: 'default' | 'development' | 'production',
) {
  const query = new URLSearchParams({ projectId, agentId, environment })
  return (
    await apiFetch(
      `/managed-agents/schedule-runs?${query.toString()}`,
      undefined,
      scheduleRunsResponseSchema,
    )
  ).runs
}

export async function runManagedAgentSchedule(
  projectId: string,
  agentId: string,
  environment: 'default' | 'development' | 'production',
  scheduleId: string,
) {
  const query = new URLSearchParams({ projectId, agentId, environment })
  return (
    await apiFetch(
      `/managed-agents/schedules/${encodeURIComponent(scheduleId)}/run?${query.toString()}`,
      { method: 'POST' },
      scheduleRunResponseSchema,
    )
  ).run
}

export async function getManagedAgentWebhooks(
  projectId: string,
  agentId: string,
  environment: 'default' | 'development' | 'production',
) {
  const query = new URLSearchParams({ agentId, environment })
  return (
    await apiFetch(
      `/managed-agents/projects/${encodeURIComponent(projectId)}/webhooks?${query.toString()}`,
      undefined,
      webhooksResponseSchema,
    )
  ).webhooks
}

export async function createManagedAgentWebhook(input: {
  projectId: string
  agentId: string
  environment: 'default' | 'development' | 'production'
  name: string
  identity?: string
}) {
  return (
    await apiFetch(
      `/managed-agents/projects/${encodeURIComponent(input.projectId)}/webhooks`,
      {
        method: 'POST',
        body: JSON.stringify({
          agentId: input.agentId,
          environment: input.environment,
          name: input.name,
          ...(input.identity ? { identity: input.identity } : {}),
        }),
      },
      webhookResponseSchema,
    )
  ).webhook
}

export async function updateManagedAgentWebhook(input: {
  projectId: string
  webhookId: string
  enabled: boolean
}) {
  return (
    await apiFetch(
      `/managed-agents/projects/${encodeURIComponent(input.projectId)}/webhooks/${encodeURIComponent(input.webhookId)}`,
      { method: 'PATCH', body: JSON.stringify({ enabled: input.enabled }) },
      webhookResponseSchema,
    )
  ).webhook
}

export async function rotateManagedAgentWebhookToken(
  projectId: string,
  webhookId: string,
) {
  return (
    await apiFetch(
      `/managed-agents/projects/${encodeURIComponent(projectId)}/webhooks/${encodeURIComponent(webhookId)}/rotate-token`,
      { method: 'POST' },
      webhookResponseSchema,
    )
  ).webhook
}

export async function deleteManagedAgentWebhook(
  projectId: string,
  webhookId: string,
) {
  return apiFetch<void>(
    `/managed-agents/projects/${encodeURIComponent(projectId)}/webhooks/${encodeURIComponent(webhookId)}`,
    { method: 'DELETE' },
  )
}

export async function startManagedAgentSlack(
  agentId: string,
  name: string,
  reconnect = false,
  channelId?: string,
) {
  return apiFetch(
    '/managed-agents/channels/slack/connections',
    {
      method: 'POST',
      body: JSON.stringify({ agentId, name, reconnect, channelId }),
    },
    slackManifestResponseSchema,
  )
}

export async function bindManagedAgentSlackDestination(
  connectionId: string,
  destination: string,
  conversationId: string,
) {
  return apiFetch(
    `/managed-agents/channels/slack/connections/${encodeURIComponent(connectionId)}/destinations/${encodeURIComponent(destination)}`,
    { method: 'PUT', body: JSON.stringify({ conversationId }) },
    z.object({
      connectionId: z.string(),
      destination: z.string(),
      conversationId: z.string(),
      displayName: z.string(),
      verifiedAt: z.string(),
    }),
  )
}

export async function completeManagedAgentSlack(
  connectionId: string,
  input: { appId: string; signingSecret: string; botToken: string },
) {
  return apiFetch(
    `/managed-agents/channels/slack/connections/${encodeURIComponent(connectionId)}`,
    { method: 'PUT', body: JSON.stringify(input) },
    channelSchema,
  )
}

export type ManagedSlackSetupTarget = {
  agentId: string
  alias: 'default' | 'development' | 'production'
  channelId?: string
}

/**
 * Start automated Slack setup, or continue the one this request key already
 * names. The same key with the same target and name returns the same record;
 * with a configuration token it also submits the app to Slack. The token is
 * request material: the platform uses it once and never stores it.
 */
export async function startManagedSlackSetup(
  input: ManagedSlackSetupTarget & {
    name: string
    requestKey: string
    configurationToken?: string
  },
) {
  return (
    await apiFetch(
      '/managed-agents/channels/slack/setups',
      { method: 'POST', body: JSON.stringify(input) },
      slackSetupResponseSchema,
    )
  ).setup
}

/** The latest resumable setup for a target, so a reloaded page finds it. */
export async function findManagedSlackSetup(target: ManagedSlackSetupTarget) {
  const query = new URLSearchParams({
    agentId: target.agentId,
    alias: target.alias,
    ...(target.channelId ? { channelId: target.channelId } : {}),
  })
  return (
    await apiFetch(
      `/managed-agents/channels/slack/setups?${query.toString()}`,
      undefined,
      slackSetupLookupSchema,
    )
  ).setup
}

export async function getManagedSlackSetup(setupId: string) {
  return (
    await apiFetch(
      `/managed-agents/channels/slack/setups/${encodeURIComponent(setupId)}`,
      undefined,
      slackSetupResponseSchema,
    )
  ).setup
}

/** A fresh authorization URL for the persisted app; earlier ones stop working. */
export async function authorizeManagedSlackSetup(setupId: string) {
  return apiFetch(
    `/managed-agents/channels/slack/setups/${encodeURIComponent(setupId)}/authorize`,
    { method: 'POST' },
    slackSetupAuthorizationSchema,
  )
}

export async function cancelManagedSlackSetup(setupId: string) {
  return (
    await apiFetch(
      `/managed-agents/channels/slack/setups/${encodeURIComponent(setupId)}/cancel`,
      { method: 'POST' },
      slackSetupResponseSchema,
    )
  ).setup
}

export async function disconnectManagedAgentSlack(connectionId: string) {
  return apiFetch(
    `/managed-agents/channels/slack/connections/${encodeURIComponent(connectionId)}`,
    { method: 'DELETE' },
    channelSchema,
  )
}

/** The project's Linear connections with health, for one environment or both. */
export async function listManagedLinearConnections(
  projectId: string,
  environment?: 'default' | 'development' | 'production',
) {
  const query = environment
    ? `?${new URLSearchParams({ environment }).toString()}`
    : ''
  return (
    await apiFetch(
      `/managed-agents/projects/${encodeURIComponent(projectId)}/linear/connections${query}`,
      undefined,
      linearConnectionsResponseSchema,
    )
  ).connections
}

/**
 * Allocate a pending connection for an agent in one environment. The answer
 * carries the webhook URL and Linear's prefilled create-app link; calling it
 * again for a binding that is still pending starts that setup over.
 */
export async function createManagedLinearConnection(input: {
  projectId: string
  environment: 'default' | 'development' | 'production'
  agentId: string
  name: string
}) {
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/linear/connections`,
    {
      method: 'POST',
      body: JSON.stringify({
        name: input.name,
        environment: input.environment,
        agentId: input.agentId,
      }),
    },
    linearCreateResponseSchema,
  )
}

/**
 * The Linear app's client ID, client secret and webhook signing secret. They
 * are sent once and never returned; the answer is the redacted connection.
 */
export async function setManagedLinearCredentials(
  connectionId: string,
  credentials: {
    clientId: string
    clientSecret: string
    signingSecret: string
  },
) {
  return (
    await apiFetch(
      `/managed-agents/linear/connections/${encodeURIComponent(connectionId)}/credentials`,
      { method: 'PUT', body: JSON.stringify(credentials) },
      linearConnectionResponseSchema,
    )
  ).connection
}

/** A fresh authorization link for the connection's app; earlier ones stop working. */
export async function authorizeManagedLinearConnection(connectionId: string) {
  return apiFetch(
    `/managed-agents/linear/connections/${encodeURIComponent(connectionId)}/authorize`,
    { method: 'POST' },
    linearAuthorizeResponseSchema,
  )
}

/** Revoke the app's access, remove the binding; the webhook URL stops working. */
export async function disconnectManagedLinearConnection(connectionId: string) {
  return apiFetch(
    `/managed-agents/linear/connections/${encodeURIComponent(connectionId)}`,
    { method: 'DELETE' },
    linearDisconnectResponseSchema,
  )
}

export async function getManagedAgentDeployment(deploymentId: string) {
  return apiFetch(
    `/managed-agents/deployments/${encodeURIComponent(deploymentId)}`,
    undefined,
    deploymentSchema,
  )
}

export async function getManagedAgentDeployments(agentId: string) {
  return (
    await apiFetch(
      `/managed-agents/deployments?agentId=${encodeURIComponent(agentId)}`,
      undefined,
      deploymentsResponseSchema,
    )
  ).deployments
}

/**
 * One page of session rows, newest first, filtered by the API rather than
 * here. `nextCursor` is null on the last page; pass it back as `cursor` to
 * continue with the same filters.
 */
export function getManagedAgentSessionsPage(
  options: {
    agentId?: string
    projectId?: string
    cursor?: string
    // Each entry filters to sessions carrying that label, sent as
    // `label.<key>=<value>` (the API allows up to three).
    labels?: Record<string, string>
  } = {},
) {
  const query = new URLSearchParams({ limit: '100' })
  if (options.agentId) query.set('agent', options.agentId)
  if (options.projectId) query.set('project', options.projectId)
  if (options.cursor) query.set('cursor', options.cursor)
  for (const [key, value] of Object.entries(options.labels ?? {})) {
    query.set(`label.${key}`, value)
  }
  return apiFetch(
    `/managed-agents/sessions?${query.toString()}`,
    undefined,
    sessionsResponseSchema,
  )
}

/** The newest page of session rows; what the single-agent view shows. */
export async function getManagedAgentSessions(
  agentId?: string,
  options: { projectId?: string } = {},
) {
  const { sessions } = await getManagedAgentSessionsPage({
    agentId,
    projectId: options.projectId,
  })
  return sessions
}

export async function collectManagedAgentEventPages(
  loadPage: (after: number) => Promise<ManagedAgentEvent[]>,
  after = 0,
) {
  const collected: ManagedAgentEvent[] = []
  let cursor = after
  for (;;) {
    const events = await loadPage(cursor)
    if (events.length === 0) return collected
    collected.push(...events)
    const nextCursor = Math.max(cursor, ...events.map((event) => event.seq))
    if (nextCursor === cursor) return collected
    cursor = nextCursor
  }
}

const workspaceFileSchema = z.object({
  path: z.string(),
  size: z.number(),
  lastModified: z.string().nullable(),
  etag: z.string().nullable(),
})
const workspaceFilesResponseSchema = z.object({
  files: z.array(workspaceFileSchema),
  nextCursor: z.string().nullable(),
})
const workspaceArtifactSchema = z.object({
  id: z.string(),
  exportId: z.string().nullish(),
  sessionId: z.string(),
  path: z.string(),
  size: z.number(),
  sha256: z.string(),
  mediaType: z.string().nullish(),
  snapshotId: z.string().nullish(),
  receipt: z.object({
    etag: z.string().nullable(),
    sourceEtag: z.string().nullable(),
    sourceVersionId: z.string().nullable(),
  }),
  exportedAt: z.string(),
})
const workspaceArtifactsResponseSchema = z.object({
  artifacts: z.array(workspaceArtifactSchema),
})
const workspaceExportResponseSchema = z.object({
  export: z.object({ id: z.string(), state: z.string() }).optional(),
  artifact: workspaceArtifactSchema.nullable(),
})
const workspaceDownloadResponseSchema = z.object({
  url: z
    .string()
    .url()
    .refine((value) => {
      const url = new URL(value)
      return url.protocol === 'https:' && !url.username && !url.password
    }),
  expiresAt: z.string(),
})
const workspaceFileDownloadResponseSchema =
  workspaceDownloadResponseSchema.extend({
    path: z.string(),
    size: z.number(),
    etag: z.string().nullable(),
    versionId: z.string().nullable(),
    lastModified: z.string().nullable(),
    mediaType: z.string(),
  })

export type ManagedWorkspaceFile = z.infer<typeof workspaceFileSchema>
export type ManagedWorkspaceArtifact = z.infer<typeof workspaceArtifactSchema>
export type ManagedWorkspaceDownload = z.infer<
  typeof workspaceFileDownloadResponseSchema
>

/** Every file the agent wrote under /workspace, across all list pages. */
export async function getManagedAgentWorkspaceFiles(sessionId: string) {
  const files: ManagedWorkspaceFile[] = []
  let cursor: string | null = null
  do {
    const query: string = cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''
    const page: z.infer<typeof workspaceFilesResponseSchema> = await apiFetch(
      `/managed-agents/sessions/${encodeURIComponent(sessionId)}/workspace/files${query}`,
      undefined,
      workspaceFilesResponseSchema,
    )
    files.push(...page.files)
    cursor = page.nextCursor
  } while (cursor)
  return files
}

export async function getManagedAgentWorkspaceArtifacts(sessionId: string) {
  return (
    await apiFetch(
      `/managed-agents/sessions/${encodeURIComponent(sessionId)}/workspace/exports`,
      undefined,
      workspaceArtifactsResponseSchema,
    )
  ).artifacts
}

export function authorizeManagedAgentWorkspaceDownload(
  sessionId: string,
  path: string,
) {
  return apiFetch(
    `/managed-agents/sessions/${encodeURIComponent(sessionId)}/workspace/download`,
    { method: 'POST', body: JSON.stringify({ path }) },
    workspaceFileDownloadResponseSchema,
  )
}

/** A normal browser download: same-origin auth redirects to signed CloudFront. */
export function managedAgentWorkspaceBrowserDownloadPath(
  sessionId: string,
  path: string,
) {
  return `/api/dashboard/managed-agents/sessions/${encodeURIComponent(sessionId)}/workspace/download?path=${encodeURIComponent(path)}`
}

/** Provider-side export: retains and hashes the file, returns its manifest. */
export async function exportManagedAgentWorkspaceFile(
  sessionId: string,
  path: string,
) {
  const result = await apiFetch(
    `/managed-agents/sessions/${encodeURIComponent(sessionId)}/workspace/exports`,
    { method: 'POST', body: JSON.stringify({ path }) },
    workspaceExportResponseSchema,
  )
  if (!result.artifact) {
    throw new Error(`Export of ${path} is still in progress; try again shortly`)
  }
  return result.artifact
}

export function managedAgentWorkspaceArtifactDownloadPath(
  artifact: Pick<ManagedWorkspaceArtifact, 'sessionId' | 'id'>,
) {
  return `/managed-agents/sessions/${encodeURIComponent(artifact.sessionId)}/workspace/exports/${encodeURIComponent(artifact.id)}/download`
}

/** Fetches a signed object without sending dashboard credentials to storage. */
export async function fetchManagedAgentWorkspaceObject(
  url: string,
  signal?: AbortSignal,
) {
  const response = await fetch(url, {
    credentials: 'omit',
    redirect: 'error',
    signal,
  })
  if (!response.ok) {
    throw new Error(`Workspace object download failed (${response.status})`)
  }
  return response
}

async function streamManagedWorkspaceDownload(
  download: ManagedWorkspaceDownload,
  write: (chunk: Uint8Array) => Promise<void>,
) {
  const response = await fetchManagedAgentWorkspaceObject(download.url)
  if (!response.body) throw new Error('Workspace file response had no body')
  const reader = response.body.getReader()
  let received = 0
  try {
    for (;;) {
      const { done, value } = await reader.read()
      if (done) break
      received += value.byteLength
      if (received > download.size) {
        throw new Error(`Download exceeded ${download.size} bytes`)
      }
      await write(value)
    }
  } catch (error) {
    await reader.cancel(error).catch(() => undefined)
    throw error
  } finally {
    reader.releaseLock()
  }
  if (received !== download.size) {
    throw new Error(`Downloaded ${received} bytes, expected ${download.size}`)
  }
}

/**
 * Streams a retained artifact chunk by chunk into `write`, hashing and
 * counting as it goes, and rejects once the stream ends unless the bytes
 * match the manifest's size and SHA-256. Callers must discard what they
 * wrote when this throws; nothing is buffered here, so a 1 GiB artifact
 * costs one chunk of memory at a time.
 */
export async function streamManagedAgentWorkspaceArtifact(
  artifact: ManagedWorkspaceArtifact,
  write: (chunk: Uint8Array) => Promise<void>,
  signal?: AbortSignal,
) {
  const handoff = await apiFetch(
    managedAgentWorkspaceArtifactDownloadPath(artifact),
    { signal },
    workspaceDownloadResponseSchema,
  )
  // This second request is deliberately unauthenticated. The signed query is
  // the authorization; platform cookies and headers must not reach storage.
  const response = await fetchManagedAgentWorkspaceObject(handoff.url, signal)
  if (!response.body) throw new Error('Artifact response had no body')
  const hash = new Sha256()
  let received = 0
  const reader = response.body.getReader()
  try {
    for (;;) {
      const { done, value } = await reader.read()
      if (done) break
      received += value.byteLength
      if (received > artifact.size) {
        throw new Error(
          `Download exceeded the manifest size of ${artifact.size} bytes`,
        )
      }
      hash.update(value)
      await write(value)
    }
  } catch (error) {
    await reader.cancel(error).catch(() => undefined)
    throw error
  } finally {
    reader.releaseLock()
  }
  if (received !== artifact.size) {
    throw new Error(
      `Downloaded ${received} bytes, manifest says ${artifact.size}`,
    )
  }
  if (hash.hex() !== artifact.sha256) {
    throw new Error('Downloaded bytes do not match the manifest SHA-256')
  }
}

/**
 * Downloads a verified artifact to the browser under `name`; on any
 * mismatch the partial output is discarded and nothing is saved. The sink
 * is opened before `resolve` runs because the save dialog needs the click's
 * user activation, which an export round-trip would outlive.
 */
export async function downloadManagedAgentWorkspaceArtifact(
  name: string,
  expectedBytes: number,
  resolve: () => Promise<ManagedWorkspaceArtifact>,
) {
  const sink = await openDownloadSink(name)
  let artifact: ManagedWorkspaceArtifact
  try {
    assertSinkCapacity(sink, expectedBytes)
    artifact = await resolve()
    assertSinkCapacity(sink, artifact.size)
    await streamManagedAgentWorkspaceArtifact(artifact, (chunk) =>
      sink.write(chunk),
    )
    await sink.close()
  } catch (error) {
    await sink.abort(error).catch(() => undefined)
    throw error
  }
  return artifact
}

function archiveBytes(entries: Array<{ path: string; size: number }>) {
  return (
    entries.reduce((sum, entry) => sum + entry.size, 0) +
    zipOverheadBytes(entries)
  )
}

/**
 * Streams several verified artifacts into a single stored zip named `name`.
 * Each entry is hashed while it is written; a mismatch aborts the whole
 * archive rather than leaving an unverifiable file behind.
 */
export async function downloadManagedAgentWorkspaceArchive(
  name: string,
  expected: Array<{ path: string; size: number }>,
  resolve: (file: {
    path: string
    size: number
  }) => Promise<ManagedWorkspaceDownload>,
  onProgress?: (done: number, total: number) => void,
) {
  const sink = await openDownloadSink(name)
  const zip = new ZipWriter(sink)
  const downloads: ManagedWorkspaceDownload[] = []
  try {
    assertSinkCapacity(sink, archiveBytes(expected))
    for (const [index, file] of expected.entries()) {
      onProgress?.(index, expected.length)
      const download = await resolve(file)
      if (download.path !== file.path) {
        throw new Error(`Workspace download path changed from ${file.path}`)
      }
      downloads.push(download)
      await zip.beginEntry(
        download.path,
        download.lastModified ? new Date(download.lastModified) : new Date(),
      )
      await streamManagedWorkspaceDownload(download, (chunk) =>
        zip.write(chunk),
      )
      await zip.endEntry()
    }
    onProgress?.(expected.length, expected.length)
    await zip.finish()
  } catch (error) {
    await zip.abort(error).catch(() => undefined)
    throw error
  }
  return downloads
}

export async function getManagedAgentSessionEvents(
  sessionId: string,
  after = 0,
  signal?: AbortSignal,
) {
  return collectManagedAgentEventPages(async (cursor) => {
    return (
      await apiFetch(
        `/managed-agents/sessions/${encodeURIComponent(sessionId)}/events?after=${cursor}`,
        signal ? { signal } : undefined,
        eventsResponseSchema,
      )
    ).events
  }, after)
}

export async function admitManagedAgentInput(
  sessionId: string,
  input: string,
  mode: ManagedAgentInputMode,
  signal?: AbortSignal,
) {
  return apiFetch(
    `/managed-agents/sessions/${encodeURIComponent(sessionId)}/turns`,
    {
      method: 'POST',
      body: JSON.stringify({
        input,
        mode,
        idempotencyKey: crypto.randomUUID(),
      }),
      signal,
    },
    turnSchema,
  )
}

async function suspendManagedAgentIfIdle(sessionId: string) {
  const session = await getManagedAgentSession(sessionId).catch(() => undefined)
  if (session?.executionMode !== 'microvm' || session.status !== 'idle') return
  await apiFetch(
    `/managed-agents/sessions/${encodeURIComponent(sessionId)}/suspend`,
    { method: 'POST' },
  ).catch(() => undefined)
}

export function managedAgentRenderDebug(event: ManagedAgentEvent) {
  if (event.type !== 'agent.rendered') return undefined
  const parsed = renderDebugSchema.safeParse(event.data)
  return parsed.success ? parsed.data : undefined
}

export function managedAgentModelRoute(event: ManagedAgentEvent) {
  if (event.type !== 'model.route_resolved') return undefined
  const parsed = modelRouteSchema.safeParse(event.data)
  return parsed.success ? parsed.data : undefined
}

export function latestManagedAgentModelRoute(events: ManagedAgentEvent[]) {
  for (let index = events.length - 1; index >= 0; index -= 1) {
    const route = managedAgentModelRoute(events[index])
    if (route) return route
  }
  return undefined
}

export async function getManagedAgentSession(sessionId: string) {
  return apiFetch(
    `/managed-agents/sessions/${encodeURIComponent(sessionId)}`,
    undefined,
    sessionSchema,
  )
}

export type ManagedMemoryEnvironment = 'default' | 'development' | 'production'

/** The complete address of one document; every read and write names it in full. */
export type ManagedMemoryDocumentTarget = {
  projectId: string
  resource: string
  id: string
  environment: ManagedMemoryEnvironment
}

type MemoryDocumentTarget = ManagedMemoryDocumentTarget

export async function getManagedMemoryResources(input: {
  projectId: string
  environment: ManagedMemoryEnvironment
}) {
  const query = new URLSearchParams({ environment: input.environment })
  return apiFetch(
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}/memory?${query.toString()}`,
    undefined,
    memoryResourceInventorySchema,
  )
}

function memoryDocumentsPath(input: {
  projectId: string
  resource: string
  environment: ManagedMemoryEnvironment
  id?: string
  cursor?: string
}) {
  const query = new URLSearchParams({ environment: input.environment })
  if (input.cursor) query.set('cursor', input.cursor)
  return (
    `/managed-agents/projects/${encodeURIComponent(input.projectId)}` +
    `/memory/${encodeURIComponent(input.resource)}/documents` +
    (input.id !== undefined ? `/${encodeURIComponent(input.id)}` : '') +
    `?${query.toString()}`
  )
}

// Reads and writes return the document with its ETag, which the next
// conditional request (If-Match) sends back verbatim.
async function memoryDocumentRequest(
  path: string,
  options: RequestInit,
): Promise<ManagedMemoryDocumentRead> {
  const response = await apiFetchResponse(path, options)
  const document = validate(memoryDocumentSchema, await response.json(), path)
  return { document, etag: response.headers.get('etag') ?? '' }
}

export async function getManagedMemoryDocuments(input: {
  projectId: string
  resource: string
  environment: ManagedMemoryEnvironment
  cursor?: string
}) {
  return apiFetch(
    memoryDocumentsPath(input),
    undefined,
    memoryDocumentPageSchema,
  )
}

export async function getManagedMemoryDocument(input: MemoryDocumentTarget) {
  return memoryDocumentRequest(memoryDocumentsPath(input), {})
}

export async function createManagedMemoryDocument(
  input: MemoryDocumentTarget & {
    title: string
    text: string
    summary?: string
    agentWrites?: 'enabled' | 'disabled'
  },
) {
  return memoryDocumentRequest(memoryDocumentsPath(input), {
    method: 'PUT',
    headers: { 'If-None-Match': '*' },
    body: JSON.stringify({
      title: input.title,
      text: input.text,
      ...(input.summary !== undefined ? { summary: input.summary } : {}),
      ...(input.agentWrites ? { agentWrites: input.agentWrites } : {}),
    }),
  })
}

export async function replaceManagedMemoryDocument(
  input: MemoryDocumentTarget & {
    etag: string
    text: string
    summary?: string
  },
) {
  return memoryDocumentRequest(memoryDocumentsPath(input), {
    method: 'PUT',
    headers: { 'If-Match': input.etag },
    body: JSON.stringify({
      text: input.text,
      ...(input.summary !== undefined ? { summary: input.summary } : {}),
    }),
  })
}

export async function patchManagedMemoryDocument(
  input: MemoryDocumentTarget & {
    etag: string
    title?: string
    agentWrites?: 'enabled' | 'disabled'
  },
) {
  return memoryDocumentRequest(memoryDocumentsPath(input), {
    method: 'PATCH',
    headers: { 'If-Match': input.etag },
    body: JSON.stringify({
      ...(input.title !== undefined ? { title: input.title } : {}),
      ...(input.agentWrites ? { agentWrites: input.agentWrites } : {}),
    }),
  })
}

export async function deleteManagedMemoryDocument(
  input: MemoryDocumentTarget & { etag: string },
) {
  return apiFetch<void>(memoryDocumentsPath(input), {
    method: 'DELETE',
    headers: { 'If-Match': input.etag },
  })
}

export function openManagedAgentEventStream(
  sessionId: string,
  after: number,
  signal?: AbortSignal,
) {
  return new ManagedAgentEventStream(sessionId, after, {
    fetchEvents: getManagedAgentSessionEvents,
    signal,
  })
}

// `timeoutMs` is an inactivity deadline: multi-step agents can run for longer
// than one fixed window while continuing to stream useful progress.
async function waitForAgentEvent(
  sessionId: string,
  after: number,
  terminal: (event: ManagedAgentEvent) => boolean,
  onEvent: (event: ManagedAgentEvent) => void,
  timeoutMs: number,
  signal?: AbortSignal,
) {
  if (signal?.aborted) throw new DOMException('Aborted', 'AbortError')
  const stream = openManagedAgentEventStream(sessionId, after, signal)
  try {
    for (;;) {
      const event = await stream.next(timeoutMs)
      onEvent(event)
      if (
        event.type === 'runtime.disconnected' ||
        event.type === 'session.failed'
      ) {
        throw new Error(
          typeof event.data.reason === 'string'
            ? event.data.reason
            : typeof event.data.message === 'string'
              ? event.data.message
              : 'The agent runtime disconnected.',
        )
      }
      if (terminal(event)) return { event, cursor: event.seq }
    }
  } catch (error) {
    if (error instanceof ManagedAgentEventStreamTimeout) {
      throw new Error('Timed out waiting for the agent.')
    }
    throw error
  } finally {
    stream.close()
  }
}

/** One memory binding on session creation; see `POST /managed-agents/sessions`. */
export type ManagedSessionMemoryBindingInput = {
  scope: 'document' | 'collection'
  id?: string
  access?: 'read' | 'read-write'
}

export async function runManagedAgent(
  agentId: string,
  input: string,
  onEvent: (event: ManagedAgentEvent) => void,
  options: {
    onSession?: (sessionId: string) => void
    signal?: AbortSignal
    memory?: Record<string, ManagedSessionMemoryBindingInput>
  } = {},
) {
  const hasMemory = options.memory && Object.keys(options.memory).length > 0
  const created = await apiFetch(
    '/managed-agents/sessions',
    {
      method: 'POST',
      body: JSON.stringify({
        agentId,
        source: 'playground',
        ...(hasMemory ? { memory: options.memory } : {}),
      }),
      signal: options.signal,
    },
    sessionCreateSchema,
  )
  const sessionId = created.session.id
  options.onSession?.(sessionId)
  try {
    let cursor = 0
    if (created.session.executionMode === 'microvm') {
      const connected = await waitForAgentEvent(
        sessionId,
        cursor,
        (event) => event.type === 'runtime.connected',
        onEvent,
        90_000,
        options.signal,
      )
      cursor = connected.cursor
    }
    const turn = await admitManagedAgentInput(
      sessionId,
      input,
      'queue',
      options.signal,
    )
    const completed = await waitForAgentEvent(
      sessionId,
      cursor,
      (event) =>
        event.turnId === turn.turnId &&
        (event.type === 'turn.completed' ||
          event.type === 'turn.failed' ||
          event.type === 'turn.cancelled'),
      onEvent,
      180_000,
      options.signal,
    )
    if (completed.event.type === 'turn.failed') {
      throw new Error(
        typeof completed.event.data.message === 'string'
          ? completed.event.data.message
          : 'The agent could not complete this request.',
      )
    }
    return { sessionId, turnId: turn.turnId }
  } finally {
    await suspendManagedAgentIfIdle(sessionId)
  }
}

/**
 * Creates a session and queues its first turn without waiting for the run to
 * finish. This is the fan-out primitive: a swarm launch calls it once per cell
 * (one agent per CVE, every repo as shared evidence), each with its own
 * findings-document binding and
 * labels that tie the session back to the run and cell, then returns the
 * session ids for the grid to poll. Unlike `runManagedAgent` it never blocks on
 * completion or suspends — the turn is admitted in `queue` mode and runs on the
 * runtime's own schedule.
 */
export async function startManagedAgentSession(
  agentId: string,
  input: string,
  options: {
    memory?: Record<string, ManagedSessionMemoryBindingInput>
    labels?: Record<string, string>
    signal?: AbortSignal
  } = {},
) {
  const hasMemory = options.memory && Object.keys(options.memory).length > 0
  const hasLabels = options.labels && Object.keys(options.labels).length > 0
  const created = await apiFetch(
    '/managed-agents/sessions',
    {
      method: 'POST',
      body: JSON.stringify({
        agentId,
        source: 'api',
        ...(hasMemory ? { memory: options.memory } : {}),
        ...(hasLabels ? { labels: options.labels } : {}),
      }),
      signal: options.signal,
    },
    sessionCreateSchema,
  )
  const sessionId = created.session.id
  const turn = await admitManagedAgentInput(
    sessionId,
    input,
    'queue',
    options.signal,
  )
  return { sessionId, turnId: turn.turnId }
}

export async function continueManagedAgentSession(
  sessionId: string,
  input: string,
  onEvent: (event: ManagedAgentEvent) => void,
  signal?: AbortSignal,
) {
  const existing = await getManagedAgentSessionEvents(sessionId)
  let cursor = existing[existing.length - 1]?.seq ?? 0
  const session = await getManagedAgentSession(sessionId)
  if (session.microvmState === 'terminated' || session.status === 'ended') {
    throw new Error('This playground session has ended. Start a new session.')
  }
  if (
    session.executionMode === 'microvm' &&
    session.microvmState === 'suspended'
  ) {
    await apiFetch(
      `/managed-agents/sessions/${encodeURIComponent(sessionId)}/resume`,
      { method: 'POST', signal },
      sessionSchema,
    )
    const connected = await waitForAgentEvent(
      sessionId,
      cursor,
      (event) => event.type === 'runtime.connected',
      onEvent,
      90_000,
      signal,
    )
    cursor = connected.cursor
  }
  try {
    const turn = await admitManagedAgentInput(sessionId, input, 'queue', signal)
    const completed = await waitForAgentEvent(
      sessionId,
      cursor,
      (event) =>
        event.turnId === turn.turnId &&
        (event.type === 'turn.completed' ||
          event.type === 'turn.failed' ||
          event.type === 'turn.cancelled'),
      onEvent,
      180_000,
      signal,
    )
    if (completed.event.type === 'turn.failed') {
      throw new Error(
        typeof completed.event.data.message === 'string'
          ? completed.event.data.message
          : 'The agent could not complete this request.',
      )
    }
    return { sessionId, turnId: turn.turnId }
  } finally {
    await suspendManagedAgentIfIdle(sessionId)
  }
}

export async function invokeManagedAgent(agentId: string, input: string) {
  const created = await apiFetch(
    '/managed-agents/sessions',
    {
      method: 'POST',
      body: JSON.stringify({ agentId }),
    },
    sessionCreateSchema,
  )
  const sessionId = created.session.id
  try {
    let cursor = 0
    if (created.session.executionMode === 'microvm') {
      const connected = await waitForAgentEvent(
        sessionId,
        cursor,
        (event) => event.type === 'runtime.connected',
        () => undefined,
        90_000,
      )
      cursor = connected.cursor
    }
    const turn = await admitManagedAgentInput(sessionId, input, 'queue')
    let streamedText = ''
    let completedText = ''
    const completed = await waitForAgentEvent(
      sessionId,
      cursor,
      (event) =>
        event.turnId === turn.turnId &&
        (event.type === 'turn.completed' ||
          event.type === 'turn.failed' ||
          event.type === 'turn.cancelled'),
      (event) => {
        if (event.type === 'message.delta') {
          streamedText +=
            typeof event.data.text === 'string' ? event.data.text : ''
        } else if (
          event.type === 'message.completed' &&
          typeof event.data.text === 'string'
        ) {
          completedText = event.data.text
        }
      },
      180_000,
    )
    if (completed.event.type === 'turn.failed') {
      throw new Error(
        typeof completed.event.data.message === 'string'
          ? completed.event.data.message
          : 'The agent could not complete this request.',
      )
    }
    return {
      sessionId,
      turnId: turn.turnId,
      output: streamedText || completedText || 'Done.',
    }
  } finally {
    await suspendManagedAgentIfIdle(sessionId)
  }
}