Skip to content

A desktop coding agent with free access to frontier models.

TypeScript
55.2 KB
Raw Blame
import {
  accessRoleValues,
  configObjectCreatedViaValues,
  configObjectSourceModeValues,
  configObjectStatusValues,
  configObjectTypeValues,
  connectorAccountStatusValues,
  connectorInstanceStatusValues,
  connectorMappingKindValues,
  connectorSyncEventTypeValues,
  connectorSyncStatusValues,
  connectorTargetKindValues,
  connectorTypeValues,
  marketplaceStatusValues,
  membershipSourceValues,
  pluginStatusValues,
} from "@omnirush-ee/den-db/schema"
import { z } from "zod"
import { denTypeIdSchema } from "../../../openapi.js"
import { idParamSchema } from "../shared.js"

const cursorSchema = z.string().trim().min(1).max(255)
const jsonObjectSchema = z.object({}).passthrough()
// MEDIUMTEXT allows ~12.58 MB of encrypted plaintext; 1 MiB stays safely below storage
// while still ~40x the largest real skill document, yielding a clean 400 instead of a 500.
const configObjectInputMaxPayloadBytes = 1_048_576
const rawSourceTextSchema = z.string().trim().min(1).refine(
  (value) => Buffer.byteLength(value, "utf8") <= configObjectInputMaxPayloadBytes,
  { message: `rawSourceText must be at most ${configObjectInputMaxPayloadBytes} bytes (1 MiB) after UTF-8 encoding.` },
)
const nullableStringSchema = z.string().trim().min(1).nullable()
const nullableTimestampSchema = z.string().datetime({ offset: true }).nullable()
const queryBooleanSchema = z.enum(["true", "false"]).transform((value) => value === "true")

export const githubWebhookEventValues = ["push", "installation", "installation_repositories", "repository"] as const

export const configObjectIdSchema = denTypeIdSchema("configObject")
export const configObjectVersionIdSchema = denTypeIdSchema("configObjectVersion")
export const configObjectAccessGrantIdSchema = denTypeIdSchema("configObjectAccessGrant")
export const pluginIdSchema = denTypeIdSchema("plugin")
export const pluginConfigObjectIdSchema = denTypeIdSchema("pluginConfigObject")
export const pluginAccessGrantIdSchema = denTypeIdSchema("pluginAccessGrant")
export const marketplaceIdSchema = denTypeIdSchema("marketplace")
export const marketplacePluginIdSchema = denTypeIdSchema("marketplacePlugin")
export const marketplaceAccessGrantIdSchema = denTypeIdSchema("marketplaceAccessGrant")
export const pluginMcpRequirementBindingIdSchema = denTypeIdSchema("pluginMcpRequirementBinding")
export const connectorAccountIdSchema = denTypeIdSchema("connectorAccount")
export const connectorInstanceIdSchema = denTypeIdSchema("connectorInstance")
export const connectorInstanceAccessGrantIdSchema = denTypeIdSchema("connectorInstanceAccessGrant")
export const connectorTargetIdSchema = denTypeIdSchema("connectorTarget")
export const connectorMappingIdSchema = denTypeIdSchema("connectorMapping")
export const connectorSyncEventIdSchema = denTypeIdSchema("connectorSyncEvent")
export const connectorSourceBindingIdSchema = denTypeIdSchema("connectorSourceBinding")
export const connectorSourceTombstoneIdSchema = denTypeIdSchema("connectorSourceTombstone")
export const memberIdSchema = denTypeIdSchema("member")
export const teamIdSchema = denTypeIdSchema("team")

export const configObjectTypeSchema = z.enum(configObjectTypeValues)
export const configObjectSourceModeSchema = z.enum(configObjectSourceModeValues)
export const configObjectCreatedViaSchema = z.enum(configObjectCreatedViaValues)
export const configObjectStatusSchema = z.enum(configObjectStatusValues)
export const pluginStatusSchema = z.enum(pluginStatusValues)
export const marketplaceStatusSchema = z.enum(marketplaceStatusValues)
export const membershipSourceSchema = z.enum(membershipSourceValues)
export const accessRoleSchema = z.enum(accessRoleValues)
export const connectorTypeSchema = z.enum(connectorTypeValues)
export const connectorAccountStatusSchema = z.enum(connectorAccountStatusValues)
export const connectorInstanceStatusSchema = z.enum(connectorInstanceStatusValues)
export const connectorTargetKindSchema = z.enum(connectorTargetKindValues)
export const connectorMappingKindSchema = z.enum(connectorMappingKindValues)
export const connectorSyncStatusSchema = z.enum(connectorSyncStatusValues)
export const connectorSyncEventTypeSchema = z.enum(connectorSyncEventTypeValues)
export const githubWebhookEventSchema = z.enum(githubWebhookEventValues)
export const extensionSourceFormatSchema = z.enum([
  "agent-plugin",
  "omnirush-builtin",
  "omnirush-extension-manifest",
  "claude-plugin",
  "opencode-plugin",
  "mcp-directory",
  "manual",
])

export const pluginArchPaginationQuerySchema = z.object({
  cursor: cursorSchema.optional(),
  limit: z.coerce.number().int().min(1).max(100).optional(),
})

export const configObjectListQuerySchema = pluginArchPaginationQuerySchema.extend({
  type: configObjectTypeSchema.optional(),
  status: configObjectStatusSchema.optional(),
  sourceMode: configObjectSourceModeSchema.optional(),
  pluginId: pluginIdSchema.optional(),
  connectorInstanceId: connectorInstanceIdSchema.optional(),
  includeDeleted: queryBooleanSchema.optional(),
  q: z.string().trim().min(1).max(255).optional(),
})

export const configObjectVersionListQuerySchema = pluginArchPaginationQuerySchema.extend({
  includeDeleted: queryBooleanSchema.optional(),
})

export const pluginListQuerySchema = pluginArchPaginationQuerySchema.extend({
  status: pluginStatusSchema.optional(),
  q: z.string().trim().min(1).max(255).optional(),
})

export const marketplaceListQuerySchema = pluginArchPaginationQuerySchema.extend({
  status: marketplaceStatusSchema.optional(),
  q: z.string().trim().min(1).max(255).optional(),
})

export const connectorAccountListQuerySchema = pluginArchPaginationQuerySchema.extend({
  connectorType: connectorTypeSchema.optional(),
  status: connectorAccountStatusSchema.optional(),
  q: z.string().trim().min(1).max(255).optional(),
})

export const connectorInstanceListQuerySchema = pluginArchPaginationQuerySchema.extend({
  connectorAccountId: connectorAccountIdSchema.optional(),
  connectorType: connectorTypeSchema.optional(),
  pluginId: pluginIdSchema.optional(),
  status: connectorInstanceStatusSchema.optional(),
  q: z.string().trim().min(1).max(255).optional(),
})

export const connectorTargetListQuerySchema = pluginArchPaginationQuerySchema.extend({
  targetKind: connectorTargetKindSchema.optional(),
  q: z.string().trim().min(1).max(255).optional(),
})

export const connectorMappingListQuerySchema = pluginArchPaginationQuerySchema.extend({
  mappingKind: connectorMappingKindSchema.optional(),
  objectType: configObjectTypeSchema.optional(),
  pluginId: pluginIdSchema.optional(),
  q: z.string().trim().min(1).max(255).optional(),
})

export const connectorSyncEventListQuerySchema = pluginArchPaginationQuerySchema.extend({
  connectorInstanceId: connectorInstanceIdSchema.optional(),
  connectorTargetId: connectorTargetIdSchema.optional(),
  eventType: connectorSyncEventTypeSchema.optional(),
  status: connectorSyncStatusSchema.optional(),
  q: z.string().trim().min(1).max(255).optional(),
})

export const githubRepositoryListQuerySchema = pluginArchPaginationQuerySchema.extend({
  q: z.string().trim().min(1).max(255).optional(),
})

export const configObjectParamsSchema = idParamSchema("configObjectId", "configObject")
export const configObjectVersionParamsSchema = configObjectParamsSchema.extend(idParamSchema("versionId", "configObjectVersion").shape)
export const configObjectAccessGrantParamsSchema = configObjectParamsSchema.extend(idParamSchema("grantId", "configObjectAccessGrant").shape)
export const pluginParamsSchema = idParamSchema("pluginId", "plugin")
export const pluginConfigObjectParamsSchema = pluginParamsSchema.extend(idParamSchema("configObjectId", "configObject").shape)
export const pluginAccessGrantParamsSchema = pluginParamsSchema.extend(idParamSchema("grantId", "pluginAccessGrant").shape)
export const marketplaceParamsSchema = idParamSchema("marketplaceId", "marketplace")
export const marketplacePluginParamsSchema = marketplaceParamsSchema.extend(idParamSchema("pluginId", "plugin").shape)
export const marketplaceAccessGrantParamsSchema = marketplaceParamsSchema.extend(idParamSchema("grantId", "marketplaceAccessGrant").shape)
export const teamParamsSchema = idParamSchema("teamId", "team")
export const connectorAccountParamsSchema = idParamSchema("connectorAccountId", "connectorAccount")
export const connectorInstanceParamsSchema = idParamSchema("connectorInstanceId", "connectorInstance")
export const connectorInstanceAccessGrantParamsSchema = connectorInstanceParamsSchema.extend(idParamSchema("grantId", "connectorInstanceAccessGrant").shape)
export const connectorTargetParamsSchema = idParamSchema("connectorTargetId", "connectorTarget")
export const connectorMappingParamsSchema = idParamSchema("connectorMappingId", "connectorMapping")
export const connectorSyncEventParamsSchema = idParamSchema("connectorSyncEventId", "connectorSyncEvent")

export const connectorAccountRepositoryParamsSchema = connectorAccountParamsSchema

export const configObjectInputSchema = z.object({
  rawSourceText: rawSourceTextSchema.optional(),
  normalizedPayloadJson: jsonObjectSchema.refine(
    (value) => Buffer.byteLength(JSON.stringify(value), "utf8") <= configObjectInputMaxPayloadBytes,
    { message: `normalizedPayloadJson must stringify to at most ${configObjectInputMaxPayloadBytes} bytes (1 MiB) after UTF-8 encoding.` },
  ).optional(),
  parserMode: z.string().trim().min(1).max(100).optional(),
  schemaVersion: z.string().trim().min(1).max(100).optional(),
  metadata: jsonObjectSchema.optional(),
}).superRefine((value, ctx) => {
  if (!value.rawSourceText && !value.normalizedPayloadJson) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "Provide either rawSourceText or normalizedPayloadJson.",
      path: ["rawSourceText"],
    })
  }
})

export const configObjectCreateSchema = z.object({
  type: configObjectTypeSchema,
  sourceMode: configObjectSourceModeSchema,
  pluginIds: z.array(pluginIdSchema).max(100).optional(),
  input: configObjectInputSchema,
})

export const configObjectCreateVersionSchema = z.object({
  input: configObjectInputSchema,
  reason: z.string().trim().min(1).max(255).optional(),
})

export const configObjectPluginAttachSchema = z.object({
  pluginId: pluginIdSchema,
  membershipSource: membershipSourceSchema.optional(),
})

export const resourceAccessGrantWriteSchema = z.object({
  orgMembershipId: memberIdSchema.optional(),
  teamId: teamIdSchema.optional(),
  orgWide: z.boolean().optional().default(false),
  role: accessRoleSchema,
}).superRefine((value, ctx) => {
  const count = Number(Boolean(value.orgMembershipId)) + Number(Boolean(value.teamId)) + Number(Boolean(value.orgWide))
  if (count !== 1) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "Provide exactly one of orgMembershipId, teamId, or orgWide=true.",
      path: ["orgMembershipId"],
    })
  }
})

/**
 * The same connector setup an admin fills in on the Connections page. It
 * configures the connection for a plugin-declared MCP server, either inline
 * while creating the plugin or later through the configure route.
 */
export const pluginMcpConnectionSetupSchema = z.object({
  authType: z.enum(["oauth", "apikey", "none"]).optional().default("oauth"),
  credentialMode: z.enum(["shared", "per_member"]).optional(),
  apiKey: z.string().trim().min(1).max(4096).optional(),
  oauthClient: z.object({
    clientId: z.string().trim().min(1).max(512),
    clientSecret: z.string().trim().min(1).max(4096).optional(),
  }).optional(),
})

export const pluginCreateComponentSchema = z.object({
  type: configObjectTypeSchema,
  input: configObjectInputSchema.optional(),
  connection: pluginMcpConnectionSetupSchema.optional(),
  connectionId: z.string().trim().min(1).max(160).optional(),
}).superRefine((value, ctx) => {
  if (value.connection && value.type !== "mcp") {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "connection is only allowed on mcp components.",
      path: ["connection"],
    })
  }
  if (value.connectionId && value.type !== "mcp") {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "connectionId is only allowed on mcp components.",
      path: ["connectionId"],
    })
  }
  if (value.connection && value.connectionId) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "Provide either connection or connectionId, not both.",
      path: ["connectionId"],
    })
  }
  if (!value.input && !value.connectionId) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "input is required unless connectionId is provided.",
      path: ["input"],
    })
  }
})

export const pluginCreateSchema = z.object({
  name: z.string().trim().min(1).max(255),
  description: nullableStringSchema.optional(),
  sourceRepositoryUrl: z.string().trim().min(1).max(1024).optional(),
  components: z.array(pluginCreateComponentSchema).max(100).optional(),
  orgWide: z.boolean().optional(),
  marketplaceId: marketplaceIdSchema.optional(),
})

export const pluginUpdateSchema = z.object({
  name: z.string().trim().min(1).max(255).optional(),
  description: nullableStringSchema.optional(),
}).superRefine((value, ctx) => {
  if (value.name === undefined && value.description === undefined) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "Provide at least one field to update.",
      path: ["name"],
    })
  }
})

export const marketplaceLogoUrlSchema = z.string().trim().min(1).max(1024).refine(
  (value) => (value.startsWith("/") ? !value.startsWith("//") : /^https:\/\//i.test(value)),
  { message: "Logo URL must be an https:// URL or a root-relative path." },
)

export const marketplaceCreateSchema = z.object({
  name: z.string().trim().min(1).max(255),
  description: nullableStringSchema.optional(),
  logoUrl: marketplaceLogoUrlSchema.nullable().optional(),
})

export const marketplaceUpdateSchema = z.object({
  name: z.string().trim().min(1).max(255).optional(),
  description: nullableStringSchema.optional(),
  logoUrl: marketplaceLogoUrlSchema.nullable().optional(),
}).superRefine((value, ctx) => {
  if (value.name === undefined && value.description === undefined && value.logoUrl === undefined) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "Provide at least one field to update.",
      path: ["name"],
    })
  }
})

export const pluginMembershipWriteSchema = z.object({
  configObjectId: configObjectIdSchema,
  membershipSource: membershipSourceSchema.optional(),
})

export const marketplacePluginWriteSchema = z.object({
  pluginId: pluginIdSchema,
  membershipSource: membershipSourceSchema.optional(),
})

export const connectorAccountCreateSchema = z.object({
  connectorType: connectorTypeSchema,
  remoteId: z.string().trim().min(1).max(255),
  externalAccountRef: z.string().trim().min(1).max(255).nullable().optional(),
  displayName: z.string().trim().min(1).max(255),
  metadata: jsonObjectSchema.optional(),
})

export const connectorAccountDisconnectSchema = z.object({
  reason: z.string().trim().min(1).max(255).optional(),
}).optional()

export const connectorInstanceCreateSchema = z.object({
  connectorAccountId: connectorAccountIdSchema,
  connectorType: connectorTypeSchema,
  remoteId: z.string().trim().min(1).max(255).nullable().optional(),
  name: z.string().trim().min(1).max(255),
  config: jsonObjectSchema.optional(),
})

export const connectorInstanceUpdateSchema = z.object({
  remoteId: z.string().trim().min(1).max(255).nullable().optional(),
  name: z.string().trim().min(1).max(255).optional(),
  status: connectorInstanceStatusSchema.optional(),
  config: jsonObjectSchema.optional(),
}).superRefine((value, ctx) => {
  if (value.remoteId === undefined && value.name === undefined && value.status === undefined && value.config === undefined) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "Provide at least one field to update.",
      path: ["name"],
    })
  }
})

export const connectorTargetCreateSchema = z.object({
  connectorType: connectorTypeSchema,
  remoteId: z.string().trim().min(1).max(255),
  targetKind: connectorTargetKindSchema,
  externalTargetRef: z.string().trim().min(1).max(255).nullable().optional(),
  config: jsonObjectSchema,
})

export const connectorTargetUpdateSchema = z.object({
  remoteId: z.string().trim().min(1).max(255).optional(),
  externalTargetRef: z.string().trim().min(1).max(255).nullable().optional(),
  config: jsonObjectSchema.optional(),
}).superRefine((value, ctx) => {
  if (value.remoteId === undefined && value.externalTargetRef === undefined && value.config === undefined) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "Provide at least one field to update.",
      path: ["remoteId"],
    })
  }
})

export const connectorMappingCreateSchema = z.object({
  mappingKind: connectorMappingKindSchema,
  selector: z.string().trim().min(1).max(255),
  objectType: configObjectTypeSchema,
  pluginId: pluginIdSchema.nullable().optional(),
  autoAddToPlugin: z.boolean().default(false),
  config: jsonObjectSchema.optional(),
})

export const connectorMappingUpdateSchema = z.object({
  selector: z.string().trim().min(1).max(255).optional(),
  objectType: configObjectTypeSchema.optional(),
  pluginId: pluginIdSchema.nullable().optional(),
  autoAddToPlugin: z.boolean().optional(),
  config: jsonObjectSchema.optional(),
}).superRefine((value, ctx) => {
  if (
    value.selector === undefined
    && value.objectType === undefined
    && value.pluginId === undefined
    && value.autoAddToPlugin === undefined
    && value.config === undefined
  ) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "Provide at least one field to update.",
      path: ["selector"],
    })
  }
})

export const githubConnectorSetupSchema = z.object({
  installationId: z.number().int().positive(),
  connectorAccountId: connectorAccountIdSchema.optional(),
  connectorInstanceName: z.string().trim().min(1).max(255),
  repositoryId: z.number().int().positive(),
  repositoryFullName: z.string().trim().min(1).max(255),
  branch: z.string().trim().min(1).max(255),
  ref: z.string().trim().min(1).max(255),
  mappings: z.array(connectorMappingCreateSchema).max(100).default([]),
})

export const githubInstallStartSchema = z.object({
  returnPath: z.string().trim().min(1).max(1024),
})

export const githubInstallCompleteSchema = z.object({
  installationId: z.number().int().positive(),
  state: z.string().trim().min(1).max(4096),
})

export const githubDiscoveryApplySchema = z.object({
  autoImportNewPlugins: z.boolean().default(false),
  selectedKeys: z.array(z.string().trim().min(1).max(255)).max(200),
})

export const githubPluginMcpImportAccessSchema = z.object({
  orgWide: z.boolean().optional().default(true),
  memberIds: z.array(memberIdSchema).max(200).optional().default([]),
  teamIds: z.array(teamIdSchema).max(200).optional().default([]),
}).superRefine((value, ctx) => {
  if (!value.orgWide && value.memberIds.length === 0 && value.teamIds.length === 0) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "Provide orgWide=true or at least one member/team grant.",
      path: ["orgWide"],
    })
  }
})

export const githubPluginMcpImportPreviewSchema = z.object({
  githubUrl: z.string().trim().url().max(2048),
})

export const githubPluginMcpImportSchema = githubPluginMcpImportPreviewSchema.extend({
  access: githubPluginMcpImportAccessSchema.optional(),
  authType: z.enum(["oauth", "none"]).optional().default("oauth"),
  credentialMode: z.enum(["shared", "per_member"]).optional().default("per_member"),
  description: z.string().trim().max(65535).nullable().optional(),
  marketplaceId: marketplaceIdSchema.optional(),
  name: z.string().trim().min(1).max(255).optional(),
  selectedSkillKeys: z.array(z.string().trim().min(1).max(1024)).max(200).optional(),
  selectedServerKeys: z.array(z.string().trim().min(1).max(1024)).max(200).optional(),
  selectedServerNames: z.array(z.string().trim().min(1).max(255)).max(200).optional(),
})

export const pluginMcpRequirementConfigureSchema = pluginMcpConnectionSetupSchema.extend({
  configObjectId: configObjectIdSchema,
  serverName: z.string().trim().min(1).max(255),
})

export const githubDiscoveryTreeQuerySchema = z.object({
  cursor: z.string().trim().min(1).max(255).optional(),
  limit: z.coerce.number().int().positive().max(500).optional(),
  prefix: z.string().trim().min(1).max(1024).optional(),
})

export const githubConnectorAccountCreateSchema = z.object({
  installationId: z.number().int().positive(),
  accountLogin: z.string().trim().min(1).max(255),
  accountType: z.enum(["Organization", "User"]),
  displayName: z.string().trim().min(1).max(255),
})

export const githubValidateTargetSchema = z.object({
  installationId: z.number().int().positive(),
  repositoryId: z.number().int().positive(),
  repositoryFullName: z.string().trim().min(1).max(255),
  branch: z.string().trim().min(1).max(255),
  ref: z.string().trim().min(1).max(255),
})

export const accessGrantSchema = z.object({
  id: z.union([configObjectAccessGrantIdSchema, pluginAccessGrantIdSchema, marketplaceAccessGrantIdSchema, connectorInstanceAccessGrantIdSchema]),
  orgMembershipId: memberIdSchema.nullable(),
  teamId: teamIdSchema.nullable(),
  orgWide: z.boolean(),
  role: accessRoleSchema,
  createdByOrgMembershipId: memberIdSchema,
  createdAt: z.string().datetime({ offset: true }),
  removedAt: nullableTimestampSchema,
}).meta({ ref: "PluginArchAccessGrant" })

export const teamPluginAccessSchema = z.object({
  plugin: z.object({
    id: pluginIdSchema,
    name: z.string().trim().min(1).max(255),
    componentCount: z.number().int().nonnegative(),
  }),
  edge: z.enum(["direct_team", "via_catalog", "org_wide"]),
  marketplace: z.object({
    id: marketplaceIdSchema,
    name: z.string().trim().min(1).max(255),
  }).nullable(),
  role: accessRoleSchema,
  grantedBy: z.object({
    orgMembershipId: memberIdSchema,
    name: z.string().trim().min(1).max(255),
  }).nullable(),
  grantedAt: z.string().datetime({ offset: true }),
  grantId: pluginAccessGrantIdSchema.nullable(),
}).meta({ ref: "PluginArchTeamPluginAccess" })

const effectiveAccessEdgeSchema = z.discriminatedUnion("kind", [
  z.object({ kind: z.literal("mine") }),
  z.object({
    kind: z.literal("person"),
    sharedBy: z.object({
      orgMembershipId: memberIdSchema,
      name: z.string().trim().min(1).max(255),
    }).nullable(),
    grantedAt: z.string().datetime({ offset: true }),
  }),
  z.object({
    kind: z.literal("team"),
    team: z.object({
      id: teamIdSchema,
      name: z.string().trim().min(1).max(255),
    }),
  }),
  z.object({ kind: z.literal("org_wide") }),
  z.object({
    kind: z.literal("catalog"),
    marketplace: z.object({
      id: marketplaceIdSchema,
      name: z.string().trim().min(1).max(255),
    }),
  }),
])

export const mePluginAccessSchema = z.object({
  plugin: z.object({
    id: pluginIdSchema,
    name: z.string().trim().min(1).max(255),
    description: nullableStringSchema,
    componentCount: z.number().int().nonnegative(),
    sourceRepositoryUrl: z.string().trim().min(1).max(1024).nullable(),
  }),
  edges: z.array(effectiveAccessEdgeSchema),
  role: accessRoleSchema,
}).meta({ ref: "PluginArchMePluginAccess" })

export const libraryItemSchema = z.discriminatedUnion("type", [
  z.object({
    type: z.literal("plugin"),
    id: pluginIdSchema,
    name: z.string().trim().min(1).max(255),
    description: nullableStringSchema,
    componentCount: z.number().int().nonnegative(),
    componentKinds: z.array(z.string()),
    sourceRepositoryUrl: z.string().trim().min(1).max(1024).nullable(),
    edges: z.array(effectiveAccessEdgeSchema),
    role: accessRoleSchema,
  }),
  z.object({
    type: z.literal("app"),
    id: configObjectIdSchema,
    pluginId: pluginIdSchema,
    name: z.string().trim().min(1).max(255),
    description: nullableStringSchema,
    sourceUrl: z.string().url().max(2048),
    status: z.enum(["active", "retired"]),
    activeVersionId: configObjectVersionIdSchema.nullable(),
    state: z.literal("ready"),
    edges: z.array(effectiveAccessEdgeSchema),
    role: accessRoleSchema,
  }),
  z.object({
    type: z.literal("connection"),
    id: z.string().trim().min(1),
    name: z.string().trim().min(1).max(255),
    url: z.string(),
    description: nullableStringSchema,
    transport: z.enum(["mcp", "native"]),
    provider: z.string().trim().min(1).nullable(),
    state: z.enum(["connected", "needs_signin", "needs_admin_setup", "available"]),
    connectedAt: nullableTimestampSchema,
    edges: z.array(effectiveAccessEdgeSchema),
  }),
  z.object({
    type: z.literal("workflow"),
    id: configObjectIdSchema,
    plugin: z.object({ id: pluginIdSchema, name: z.string().trim().min(1).max(255) }).nullable(),
    name: z.string().trim().min(1).max(255),
    description: nullableStringSchema,
    role: accessRoleSchema,
    edges: z.array(effectiveAccessEdgeSchema),
    state: z.enum(["ready", "needs_signin", "needs_admin_setup"]),
    resultState: z.enum(["never_run", "fresh", "stale", "needs_attention"]),
    latestSuccessfulAt: nullableTimestampSchema,
    viewState: z.enum(["default", "custom_active", "build_failed", "retired"]),
    activeViewTitle: nullableStringSchema,
    automationCount: z.number().int().nonnegative(),
    source: z.object({
      kind: z.enum(["created", "installed_template"]),
      templateName: z.string().trim().min(1).max(255).optional(),
      templateVersion: z.string().trim().min(1).max(100).optional(),
    }),
  }),
]).meta({ ref: "PluginArchLibraryItem" })

export const meLibraryListResponseSchema = z.object({
  items: z.array(libraryItemSchema),
}).meta({ ref: "PluginArchMeLibraryListResponse" })

export const configObjectVersionSchema = z.object({
  id: configObjectVersionIdSchema,
  configObjectId: configObjectIdSchema,
  schemaVersion: z.string().trim().min(1).max(100).nullable(),
  normalizedPayloadJson: jsonObjectSchema.nullable(),
  rawSourceText: z.string().nullable(),
  createdVia: configObjectCreatedViaSchema,
  createdByOrgMembershipId: memberIdSchema.nullable(),
  connectorSyncEventId: connectorSyncEventIdSchema.nullable(),
  sourceRevisionRef: z.string().trim().min(1).max(255).nullable(),
  isDeletedVersion: z.boolean(),
  createdAt: z.string().datetime({ offset: true }),
}).meta({ ref: "PluginArchConfigObjectVersion" })

export const configObjectSchema = z.object({
  id: configObjectIdSchema,
  organizationId: denTypeIdSchema("organization"),
  objectType: configObjectTypeSchema,
  sourceMode: configObjectSourceModeSchema,
  title: z.string().trim().min(1).max(255),
  description: nullableStringSchema,
  searchText: z.string().trim().min(1).max(65535).nullable(),
  currentFileName: z.string().trim().min(1).max(255).nullable(),
  currentFileExtension: z.string().trim().min(1).max(32).nullable(),
  currentRelativePath: z.string().trim().min(1).max(255).nullable(),
  status: configObjectStatusSchema,
  createdByOrgMembershipId: memberIdSchema,
  connectorInstanceId: connectorInstanceIdSchema.nullable(),
  createdAt: z.string().datetime({ offset: true }),
  updatedAt: z.string().datetime({ offset: true }),
  deletedAt: nullableTimestampSchema,
  latestVersion: configObjectVersionSchema.nullable(),
}).meta({ ref: "PluginArchConfigObject" })

export const pluginMembershipSchema = z.object({
  id: pluginConfigObjectIdSchema,
  pluginId: pluginIdSchema,
  configObjectId: configObjectIdSchema,
  membershipSource: membershipSourceSchema,
  connectorMappingId: connectorMappingIdSchema.nullable(),
  createdByOrgMembershipId: memberIdSchema.nullable(),
  createdAt: z.string().datetime({ offset: true }),
  removedAt: nullableTimestampSchema,
  configObject: configObjectSchema.optional(),
}).meta({ ref: "PluginArchPluginMembership" })

export const extensionManifestSchema = z.object({
  schemaVersion: z.literal(1),
  id: z.string().trim().min(1).max(255),
  name: z.string().trim().min(1).max(255),
  description: z.string().trim().min(1).max(2048),
  source: z.object({
    format: extensionSourceFormatSchema,
    trusted: z.boolean(),
    origin: z.enum(["builtin", "den", "workspace", "local"]).optional(),
    reference: z.string().trim().min(1).max(512).optional(),
  }),
  resources: z.array(jsonObjectSchema),
  contributions: z.array(jsonObjectSchema).optional(),
  setup: jsonObjectSchema.optional(),
  lifecycle: jsonObjectSchema.optional(),
}).passthrough().meta({ ref: "OmniRushExtensionManifest" })

export const pluginExtensionSchema = z.object({
  id: pluginIdSchema,
  name: z.string().trim().min(1).max(255),
  description: nullableStringSchema,
  sourceFormat: extensionSourceFormatSchema,
  manifest: extensionManifestSchema.nullable(),
}).meta({ ref: "PluginArchExtensionProjection" })

export const pluginSchema = z.object({
  id: pluginIdSchema,
  organizationId: denTypeIdSchema("organization"),
  name: z.string().trim().min(1).max(255),
  description: nullableStringSchema,
  sourceRepositoryUrl: z.string().trim().min(1).max(1024).nullable(),
  sourceFormat: extensionSourceFormatSchema.nullable(),
  sourceSchemaVersion: z.string().trim().min(1).max(100).nullable(),
  status: pluginStatusSchema,
  createdByOrgMembershipId: memberIdSchema,
  createdAt: z.string().datetime({ offset: true }),
  updatedAt: z.string().datetime({ offset: true }),
  deletedAt: nullableTimestampSchema,
  memberCount: z.number().int().nonnegative().optional(),
  marketplaces: z.array(z.object({
    id: marketplaceIdSchema,
    name: z.string().trim().min(1).max(255),
  })).optional(),
  extension: pluginExtensionSchema.nullable().optional(),
}).meta({ ref: "PluginArchPlugin" })

export const marketplacePluginSchema = z.object({
  id: marketplacePluginIdSchema,
  marketplaceId: marketplaceIdSchema,
  pluginId: pluginIdSchema,
  membershipSource: membershipSourceSchema,
  createdByOrgMembershipId: memberIdSchema.nullable(),
  createdAt: z.string().datetime({ offset: true }),
  removedAt: nullableTimestampSchema,
  plugin: pluginSchema.optional(),
}).meta({ ref: "PluginArchMarketplacePluginMembership" })

export const marketplaceSchema = z.object({
  externalKey: z.string().nullable(),
  id: marketplaceIdSchema,
  organizationId: denTypeIdSchema("organization"),
  name: z.string().trim().min(1).max(255),
  description: nullableStringSchema,
  logoUrl: nullableStringSchema,
  status: marketplaceStatusSchema,
  createdByOrgMembershipId: memberIdSchema,
  createdAt: z.string().datetime({ offset: true }),
  updatedAt: z.string().datetime({ offset: true }),
  deletedAt: nullableTimestampSchema,
  pluginCount: z.number().int().nonnegative().optional(),
}).meta({ ref: "PluginArchMarketplace" })

const pluginCloudReadinessSchema = z.object({
  state: z.enum(["ready", "needs_signin", "needs_admin_setup", "desktop_only", "not_synced"]),
  hasInstructional: z.boolean(),
  connections: z.array(z.object({
    authType: z.enum(["oauth", "apikey", "none"]).optional(),
    authTypeMismatch: z.boolean().optional(),
    configObjectId: configObjectIdSchema,
    id: z.string().nullable(),
    name: z.string(),
    serverName: z.string(),
    url: z.string(),
    credentialMode: z.enum(["shared", "per_member"]).optional(),
    connectedForMe: z.boolean().optional(),
    oauthClientConfigured: z.boolean().optional(),
    oauthClientRequired: z.boolean().optional(),
    requiredAuthType: z.enum(["oauth", "apikey", "none"]).optional(),
  })),
}).meta({ ref: "PluginArchPluginCloudReadiness" })

export const connectorAccountSchema = z.object({
  id: connectorAccountIdSchema,
  organizationId: denTypeIdSchema("organization"),
  connectorType: connectorTypeSchema,
  remoteId: z.string().trim().min(1).max(255),
  externalAccountRef: z.string().trim().min(1).max(255).nullable(),
  displayName: z.string().trim().min(1).max(255),
  status: connectorAccountStatusSchema,
  createdByName: z.string().trim().min(1).max(255).nullable().optional(),
  createdByOrgMembershipId: memberIdSchema,
  createdAt: z.string().datetime({ offset: true }),
  updatedAt: z.string().datetime({ offset: true }),
  metadata: jsonObjectSchema.optional(),
}).meta({ ref: "PluginArchConnectorAccount" })

export const connectorInstanceSchema = z.object({
  id: connectorInstanceIdSchema,
  organizationId: denTypeIdSchema("organization"),
  connectorAccountId: connectorAccountIdSchema,
  connectorType: connectorTypeSchema,
  remoteId: z.string().trim().min(1).max(255).nullable(),
  name: z.string().trim().min(1).max(255),
  status: connectorInstanceStatusSchema,
  instanceConfigJson: jsonObjectSchema.nullable(),
  lastSyncedAt: nullableTimestampSchema,
  lastSyncStatus: connectorSyncStatusSchema.nullable(),
  lastSyncCursor: z.string().trim().min(1).max(255).nullable(),
  createdByOrgMembershipId: memberIdSchema,
  createdAt: z.string().datetime({ offset: true }),
  updatedAt: z.string().datetime({ offset: true }),
}).meta({ ref: "PluginArchConnectorInstance" })

export const connectorTargetSchema = z.object({
  id: connectorTargetIdSchema,
  connectorInstanceId: connectorInstanceIdSchema,
  connectorType: connectorTypeSchema,
  remoteId: z.string().trim().min(1).max(255),
  targetKind: connectorTargetKindSchema,
  externalTargetRef: z.string().trim().min(1).max(255).nullable(),
  targetConfigJson: jsonObjectSchema,
  createdAt: z.string().datetime({ offset: true }),
  updatedAt: z.string().datetime({ offset: true }),
}).meta({ ref: "PluginArchConnectorTarget" })

export const connectorMappingSchema = z.object({
  id: connectorMappingIdSchema,
  connectorInstanceId: connectorInstanceIdSchema,
  connectorTargetId: connectorTargetIdSchema,
  connectorType: connectorTypeSchema,
  remoteId: z.string().trim().min(1).max(255).nullable(),
  mappingKind: connectorMappingKindSchema,
  selector: z.string().trim().min(1).max(255),
  objectType: configObjectTypeSchema,
  pluginId: pluginIdSchema.nullable(),
  autoAddToPlugin: z.boolean(),
  mappingConfigJson: jsonObjectSchema.nullable(),
  createdAt: z.string().datetime({ offset: true }),
  updatedAt: z.string().datetime({ offset: true }),
}).meta({ ref: "PluginArchConnectorMapping" })

export const connectorSyncSummarySchema = z.object({
  createdCount: z.number().int().nonnegative().optional(),
  updatedCount: z.number().int().nonnegative().optional(),
  deletedCount: z.number().int().nonnegative().optional(),
  skippedCount: z.number().int().nonnegative().optional(),
  failedCount: z.number().int().nonnegative().optional(),
  failures: z.array(jsonObjectSchema).optional(),
}).passthrough().meta({ ref: "PluginArchConnectorSyncSummary" })

export const connectorSyncEventSchema = z.object({
  id: connectorSyncEventIdSchema,
  attemptCount: z.number().int().nonnegative(),
  connectorInstanceId: connectorInstanceIdSchema,
  connectorTargetId: connectorTargetIdSchema.nullable(),
  connectorType: connectorTypeSchema,
  remoteId: z.string().trim().min(1).max(255).nullable(),
  eventType: connectorSyncEventTypeSchema,
  externalEventRef: z.string().trim().min(1).max(255).nullable(),
  sourceRevisionRef: z.string().trim().min(1).max(255).nullable(),
  nextAttemptAt: nullableTimestampSchema,
  status: connectorSyncStatusSchema,
  summaryJson: connectorSyncSummarySchema.nullable(),
  startedAt: z.string().datetime({ offset: true }),
  completedAt: nullableTimestampSchema,
}).meta({ ref: "PluginArchConnectorSyncEvent" })

export const connectorSourceBindingSchema = z.object({
  id: connectorSourceBindingIdSchema,
  configObjectId: configObjectIdSchema,
  connectorInstanceId: connectorInstanceIdSchema,
  connectorTargetId: connectorTargetIdSchema,
  connectorMappingId: connectorMappingIdSchema,
  connectorType: connectorTypeSchema,
  remoteId: z.string().trim().min(1).max(255).nullable(),
  externalLocator: z.string().trim().min(1).max(255),
  externalStableRef: z.string().trim().min(1).max(255).nullable(),
  lastSeenSourceRevisionRef: z.string().trim().min(1).max(255).nullable(),
  status: configObjectStatusSchema,
  createdAt: z.string().datetime({ offset: true }),
  updatedAt: z.string().datetime({ offset: true }),
  deletedAt: nullableTimestampSchema,
}).meta({ ref: "PluginArchConnectorSourceBinding" })

export const connectorSourceTombstoneSchema = z.object({
  id: connectorSourceTombstoneIdSchema,
  connectorInstanceId: connectorInstanceIdSchema,
  connectorTargetId: connectorTargetIdSchema,
  connectorMappingId: connectorMappingIdSchema,
  connectorType: connectorTypeSchema,
  remoteId: z.string().trim().min(1).max(255).nullable(),
  externalLocator: z.string().trim().min(1).max(255),
  formerConfigObjectId: configObjectIdSchema,
  deletedInSyncEventId: connectorSyncEventIdSchema,
  deletedSourceRevisionRef: z.string().trim().min(1).max(255).nullable(),
  createdAt: z.string().datetime({ offset: true }),
}).meta({ ref: "PluginArchConnectorSourceTombstone" })

export const githubWebhookHeadersSchema = z.object({
  xHubSignature256: z.string().trim().min(1),
  xGithubEvent: githubWebhookEventSchema,
  xGithubDelivery: z.string().trim().min(1),
}).meta({ ref: "PluginArchGithubWebhookHeaders" })

export const githubWebhookPayloadSchema = z.object({
  after: z.string().trim().min(1).optional(),
  installation: z.object({
    id: z.number().int().positive(),
  }).passthrough().optional(),
  ref: z.string().trim().min(1).optional(),
  repository: z.object({
    full_name: z.string().trim().min(1),
    id: z.number().int().positive(),
  }).passthrough().optional(),
}).passthrough().meta({ ref: "PluginArchGithubWebhookPayload" })

export const githubWebhookEnvelopeSchema = z.object({
  deliveryId: z.string().trim().min(1),
  event: githubWebhookEventSchema,
  installationId: z.number().int().positive().optional(),
  repositoryId: z.number().int().positive().optional(),
  repositoryFullName: z.string().trim().min(1).optional(),
  ref: z.string().trim().min(1).optional(),
  headSha: z.string().trim().min(1).optional(),
  payload: githubWebhookPayloadSchema,
}).meta({ ref: "PluginArchGithubWebhookEnvelope" })

export const githubConnectorSyncJobSchema = z.object({
  connectorType: z.literal("github"),
  connectorInstanceId: connectorInstanceIdSchema,
  connectorTargetId: connectorTargetIdSchema,
  connectorSyncEventId: connectorSyncEventIdSchema,
  deliveryId: z.string().trim().min(1),
  installationId: z.number().int().positive(),
  repositoryId: z.number().int().positive(),
  repositoryFullName: z.string().trim().min(1),
  ref: z.string().trim().min(1),
  headSha: z.string().trim().min(1),
}).meta({ ref: "PluginArchGithubConnectorSyncJob" })

export const githubWebhookRawBodySchema = z.string().min(1).meta({ ref: "PluginArchGithubWebhookRawBody" })

export const githubWebhookAcceptedResponseSchema = z.object({
  ok: z.literal(true),
  accepted: z.literal(true),
  event: githubWebhookEventSchema,
  deliveryId: z.string().trim().min(1),
  queued: z.boolean(),
}).meta({ ref: "PluginArchGithubWebhookAcceptedResponse" })

export const githubWebhookIgnoredResponseSchema = z.object({
  ok: z.literal(true),
  accepted: z.literal(false),
  reason: z.string().trim().min(1),
}).meta({ ref: "PluginArchGithubWebhookIgnoredResponse" })

export const githubWebhookUnauthorizedResponseSchema = z.object({
  ok: z.literal(false),
  error: z.literal("invalid signature"),
}).meta({ ref: "PluginArchGithubWebhookUnauthorizedResponse" })

export function pluginArchListResponseSchema<TSchema extends z.ZodTypeAny>(ref: string, itemSchema: TSchema) {
  return z.object({
    items: z.array(itemSchema),
    nextCursor: cursorSchema.nullable(),
  }).meta({ ref })
}

export function pluginArchDetailResponseSchema<TSchema extends z.ZodTypeAny>(ref: string, itemSchema: TSchema) {
  return z.object({
    item: itemSchema,
  }).meta({ ref })
}

export function pluginArchMutationResponseSchema<TSchema extends z.ZodTypeAny>(ref: string, itemSchema: TSchema) {
  return z.object({
    ok: z.literal(true),
    item: itemSchema,
  }).meta({ ref })
}

export function pluginArchAsyncResponseSchema<TSchema extends z.ZodTypeAny>(ref: string, jobSchema: TSchema) {
  return z.object({
    ok: z.literal(true),
    queued: z.literal(true),
    job: jobSchema,
  }).meta({ ref })
}

export const configObjectListResponseSchema = pluginArchListResponseSchema("PluginArchConfigObjectListResponse", configObjectSchema)
export const configObjectDetailResponseSchema = pluginArchDetailResponseSchema("PluginArchConfigObjectDetailResponse", configObjectSchema)
export const configObjectMutationResponseSchema = pluginArchMutationResponseSchema("PluginArchConfigObjectMutationResponse", configObjectSchema)
export const configObjectVersionListResponseSchema = pluginArchListResponseSchema("PluginArchConfigObjectVersionListResponse", configObjectVersionSchema)
export const configObjectVersionDetailResponseSchema = pluginArchDetailResponseSchema("PluginArchConfigObjectVersionDetailResponse", configObjectVersionSchema)
export const pluginListResponseSchema = pluginArchListResponseSchema("PluginArchPluginListResponse", pluginSchema)
export const pluginDetailResponseSchema = pluginArchDetailResponseSchema("PluginArchPluginDetailResponse", pluginSchema)
export const pluginMutationResponseSchema = pluginArchMutationResponseSchema("PluginArchPluginMutationResponse", pluginSchema)
export const pluginMembershipListResponseSchema = pluginArchListResponseSchema("PluginArchPluginMembershipListResponse", pluginMembershipSchema)
export const pluginMembershipDetailResponseSchema = pluginArchDetailResponseSchema("PluginArchPluginMembershipDetailResponse", pluginMembershipSchema)
export const pluginMembershipMutationResponseSchema = pluginArchMutationResponseSchema("PluginArchPluginMembershipMutationResponse", pluginMembershipSchema)
export const marketplaceListResponseSchema = pluginArchListResponseSchema("PluginArchMarketplaceListResponse", marketplaceSchema)
export const marketplaceDetailResponseSchema = pluginArchDetailResponseSchema("PluginArchMarketplaceDetailResponse", marketplaceSchema)
export const marketplaceMutationResponseSchema = pluginArchMutationResponseSchema("PluginArchMarketplaceMutationResponse", marketplaceSchema)

export const marketplaceResolvedResponseSchema = pluginArchMutationResponseSchema(
  "PluginArchMarketplaceResolvedResponse",
  z.object({
    marketplace: marketplaceSchema.extend({
      canDelete: z.boolean(),
    }),
    plugins: z.array(pluginSchema.extend({
      componentCounts: z.record(z.string(), z.number().int().nonnegative()).default({}),
      cloudReadiness: pluginCloudReadinessSchema.optional(),
    })),
    source: z.object({
      connectorAccountId: connectorAccountIdSchema,
      connectorInstanceId: connectorInstanceIdSchema,
      accountLogin: z.string().trim().min(1).nullable(),
      repositoryFullName: z.string().trim().min(1),
      branch: z.string().trim().min(1).nullable(),
    }).nullable(),
  }),
)

const githubPluginMcpImportServerSchema = z.object({
  authType: z.literal("oauth").nullable(),
  connectionId: z.string().nullable(),
  name: z.string(),
  pluginKey: z.string(),
  pluginName: z.string(),
  serverKey: z.string(),
  skippedReason: z.enum(["headers_unsupported", "invalid_config", "invalid_url", "local_unsupported", "missing_url", "unsupported_auth"]).nullable(),
  sourceSchemaVersion: z.string().nullable(),
  sourcePath: z.string(),
  supported: z.boolean(),
  url: z.string().nullable(),
}).meta({ ref: "GithubPluginMcpImportServer" })

const githubPluginMcpImportPlanSchema = z.object({
  branch: z.string(),
  classification: z.enum(["agent_plugin_repo", "claude_marketplace_repo", "claude_multi_plugin_repo", "claude_single_plugin_repo", "folder_inferred_repo", "unsupported"]),
  marketplace: z.object({
    description: z.string().nullable(),
    name: z.string().nullable(),
    owner: z.string().nullable(),
    version: z.string().nullable(),
  }).nullable(),
  plugins: z.array(z.object({
    description: z.string().nullable(),
    key: z.string(),
    mcpCount: z.number().int().nonnegative(),
    name: z.string(),
    skillCount: z.number().int().nonnegative(),
  })),
  repositoryFullName: z.string(),
  rootPath: z.string(),
  servers: z.array(githubPluginMcpImportServerSchema),
  skills: z.array(z.object({
    description: z.string().nullable(),
    name: z.string(),
    pluginKey: z.string(),
    pluginName: z.string(),
    skillKey: z.string(),
    skippedReason: z.enum(["invalid_skill"]).nullable(),
    sourceSchemaVersion: z.string().nullable(),
    sourcePath: z.string(),
    supported: z.boolean(),
  })),
  sourceSchemaVersion: z.string().nullable(),
  sourceRevisionRef: z.string(),
  warnings: z.array(z.string()),
}).meta({ ref: "GithubPluginMcpImportPlan" })

export const githubPluginMcpImportPreviewResponseSchema = pluginArchMutationResponseSchema(
  "GithubPluginMcpImportPreviewResponse",
  githubPluginMcpImportPlanSchema,
)

export const githubPluginMcpImportResponseSchema = pluginArchMutationResponseSchema(
  "GithubPluginMcpImportResponse",
  z.object({
    imported: z.array(z.object({
      connectionId: z.string(),
      name: z.string(),
      url: z.string(),
    })),
    importedSkills: z.array(z.object({
      configObjectId: configObjectIdSchema,
      name: z.string(),
      sourcePath: z.string(),
    })),
    marketplaceId: marketplaceIdSchema.nullable(),
    plugin: pluginSchema,
    skipped: z.array(z.object({
      name: z.string(),
      reason: z.enum(["headers_unsupported", "invalid_config", "invalid_url", "local_unsupported", "missing_url", "unsupported_auth"]),
    })),
    skippedSkills: z.array(z.object({
      name: z.string(),
      reason: z.enum(["invalid_skill"]),
      sourcePath: z.string(),
    })),
  }),
)
export const pluginMcpRequirementConfigureResponseSchema = pluginArchMutationResponseSchema(
  "PluginArchPluginMcpRequirementConfigureResponse",
  z.object({
    binding: z.object({
      id: pluginMcpRequirementBindingIdSchema,
      configObjectId: configObjectIdSchema,
      externalMcpConnectionId: z.string(),
      pluginId: pluginIdSchema,
      serverName: z.string(),
    }),
    connection: z.object({
      id: z.string(),
      name: z.string(),
      url: z.string(),
      authType: z.enum(["oauth", "apikey", "none"]),
      credentialMode: z.enum(["shared", "per_member"]),
      connected: z.boolean(),
      connectedAt: nullableTimestampSchema,
    }),
    links: z.object({
      yourConnections: z.string(),
    }),
  }),
)
export const marketplacePluginListResponseSchema = pluginArchListResponseSchema("PluginArchMarketplacePluginListResponse", marketplacePluginSchema)
export const marketplacePluginMutationResponseSchema = pluginArchMutationResponseSchema("PluginArchMarketplacePluginMutationResponse", marketplacePluginSchema)
export const accessGrantListResponseSchema = pluginArchListResponseSchema("PluginArchAccessGrantListResponse", accessGrantSchema)
export const accessGrantMutationResponseSchema = pluginArchMutationResponseSchema("PluginArchAccessGrantMutationResponse", accessGrantSchema)
export const teamPluginAccessListResponseSchema = pluginArchListResponseSchema("PluginArchTeamPluginAccessListResponse", teamPluginAccessSchema).omit({ nextCursor: true })
export const mePluginAccessListResponseSchema = pluginArchListResponseSchema("PluginArchMePluginAccessListResponse", mePluginAccessSchema).omit({ nextCursor: true })
export const connectorAccountListResponseSchema = pluginArchListResponseSchema("PluginArchConnectorAccountListResponse", connectorAccountSchema)
export const connectorAccountDetailResponseSchema = pluginArchDetailResponseSchema("PluginArchConnectorAccountDetailResponse", connectorAccountSchema)
export const connectorAccountMutationResponseSchema = pluginArchMutationResponseSchema("PluginArchConnectorAccountMutationResponse", connectorAccountSchema)
export const connectorAccountDisconnectResponseSchema = pluginArchMutationResponseSchema(
  "PluginArchConnectorAccountDisconnectResponse",
  z.object({
    deletedConfigObjectCount: z.number().int().nonnegative(),
    deletedConnectorInstanceCount: z.number().int().nonnegative(),
    deletedConnectorMappingCount: z.number().int().nonnegative(),
    disconnectedAccountId: connectorAccountIdSchema,
    reason: z.string().trim().nullable(),
  }),
)
export const connectorInstanceConfiguredPluginSchema = pluginSchema.extend({
  componentCounts: z.record(z.string(), z.number().int().nonnegative()).default({}),
  rootPath: z.string().nullable(),
}).meta({ ref: "PluginArchConnectorInstanceConfiguredPlugin" })

export const connectorInstanceConfigurationResponseSchema = pluginArchMutationResponseSchema(
  "PluginArchConnectorInstanceConfigurationResponse",
  z.object({
    autoImportNewPlugins: z.boolean(),
    configuredPlugins: z.array(connectorInstanceConfiguredPluginSchema),
    connectorInstance: connectorInstanceSchema,
    importedConfigObjectCount: z.number().int().nonnegative(),
    mappingCount: z.number().int().nonnegative(),
  }),
)
export const connectorInstanceAutoImportSchema = z.object({
  autoImportNewPlugins: z.boolean(),
})
export const connectorInstanceRemoveResponseSchema = pluginArchMutationResponseSchema(
  "PluginArchConnectorInstanceRemoveResponse",
  z.object({
    deletedConfigObjectCount: z.number().int().nonnegative(),
    deletedConnectorMappingCount: z.number().int().nonnegative(),
    removedConnectorInstanceId: connectorInstanceIdSchema,
  }),
)
export const connectorInstanceListResponseSchema = pluginArchListResponseSchema("PluginArchConnectorInstanceListResponse", connectorInstanceSchema)
export const connectorInstanceDetailResponseSchema = pluginArchDetailResponseSchema("PluginArchConnectorInstanceDetailResponse", connectorInstanceSchema)
export const connectorInstanceMutationResponseSchema = pluginArchMutationResponseSchema("PluginArchConnectorInstanceMutationResponse", connectorInstanceSchema)
export const connectorInstanceSyncNowResponseSchema = pluginArchMutationResponseSchema(
  "PluginArchConnectorInstanceSyncNowResponse",
  z.object({ enqueuedCount: z.number().int().nonnegative() }),
)
export const connectorTargetListResponseSchema = pluginArchListResponseSchema("PluginArchConnectorTargetListResponse", connectorTargetSchema)
export const connectorTargetDetailResponseSchema = pluginArchDetailResponseSchema("PluginArchConnectorTargetDetailResponse", connectorTargetSchema)
export const connectorTargetMutationResponseSchema = pluginArchMutationResponseSchema("PluginArchConnectorTargetMutationResponse", connectorTargetSchema)
export const connectorMappingListResponseSchema = pluginArchListResponseSchema("PluginArchConnectorMappingListResponse", connectorMappingSchema)
export const connectorMappingMutationResponseSchema = pluginArchMutationResponseSchema("PluginArchConnectorMappingMutationResponse", connectorMappingSchema)
export const connectorSyncEventListResponseSchema = pluginArchListResponseSchema("PluginArchConnectorSyncEventListResponse", connectorSyncEventSchema)
export const connectorSyncEventDetailResponseSchema = pluginArchDetailResponseSchema("PluginArchConnectorSyncEventDetailResponse", connectorSyncEventSchema)
export const connectorSyncAsyncResponseSchema = pluginArchAsyncResponseSchema(
  "PluginArchConnectorSyncAsyncResponse",
  z.object({ id: connectorSyncEventIdSchema }),
)
export const githubRepositorySchema = z.object({
  id: z.number().int().positive(),
  fullName: z.string().trim().min(1),
  defaultBranch: z.string().trim().min(1).nullable(),
  hasPluginManifest: z.boolean().optional(),
  manifestKind: z.enum(["agent-plugin", "marketplace", "plugin"]).nullable().optional(),
  marketplacePluginCount: z.number().int().nonnegative().nullable().optional(),
  private: z.boolean(),
}).meta({ ref: "PluginArchGithubRepository" })
export const githubRepositoryListResponseSchema = pluginArchListResponseSchema("PluginArchGithubRepositoryListResponse", githubRepositorySchema)
export const githubDiscoveryStepSchema = z.object({
  id: z.enum(["read_repository_structure", "check_marketplace_manifest", "check_plugin_manifests", "prepare_discovered_plugins"]),
  label: z.string().trim().min(1),
  status: z.enum(["completed", "running", "warning"]),
}).meta({ ref: "PluginArchGithubDiscoveryStep" })
export const githubDiscoveryTreeSummarySchema = z.object({
  scannedEntryCount: z.number().int().nonnegative(),
  strategy: z.enum(["git-tree-recursive"]),
  truncated: z.boolean(),
}).meta({ ref: "PluginArchGithubDiscoveryTreeSummary" })
export const githubDiscoveredPluginSchema = z.object({
  key: z.string().trim().min(1),
  sourceKind: z.enum(["agent_plugin_manifest", "marketplace_entry", "plugin_manifest", "standalone_claude", "folder_inference"]),
  sourceSchemaVersion: z.enum(["1.0.0", "1.1.0"]).nullable(),
  rootPath: z.string(),
  displayName: z.string().trim().min(1),
  description: nullableStringSchema,
  selectedByDefault: z.boolean(),
  supported: z.boolean(),
  manifestPath: nullableStringSchema,
  warnings: z.array(z.string().trim().min(1)),
  componentKinds: z.array(z.enum(["skill", "command", "agent", "hook", "mcp_server", "lsp_server", "monitor", "settings"])),
  componentPaths: z.object({
    agents: z.array(z.string().trim().min(1)),
    commands: z.array(z.string().trim().min(1)),
    hooks: z.array(z.string().trim().min(1)),
    lspServers: z.array(z.string().trim().min(1)),
    mcpServers: z.array(z.string().trim().min(1)),
    monitors: z.array(z.string().trim().min(1)),
    settings: z.array(z.string().trim().min(1)),
    skills: z.array(z.string().trim().min(1)),
  }),
  metadata: jsonObjectSchema,
}).meta({ ref: "PluginArchGithubDiscoveredPlugin" })
export const githubConnectorDiscoveryResponseSchema = pluginArchMutationResponseSchema(
  "PluginArchGithubConnectorDiscoveryResponse",
  z.object({
    autoImportNewPlugins: z.boolean(),
    classification: z.enum(["agent_plugin_repo", "claude_marketplace_repo", "claude_multi_plugin_repo", "claude_single_plugin_repo", "folder_inferred_repo", "unsupported"]),
    connectorInstance: connectorInstanceSchema,
    connectorTarget: connectorTargetSchema,
    discoveredPlugins: z.array(githubDiscoveredPluginSchema),
    repositoryFullName: z.string().trim().min(1),
    sourceRevisionRef: z.string().trim().min(1),
    steps: z.array(githubDiscoveryStepSchema),
    treeSummary: githubDiscoveryTreeSummarySchema,
    warnings: z.array(z.string().trim().min(1)),
  }),
)
export const githubDiscoveryTreeEntrySchema = z.object({
  id: z.string().trim().min(1),
  kind: z.enum(["blob", "tree"]),
  path: z.string().trim().min(1),
  sha: nullableStringSchema,
  size: z.number().int().nonnegative().nullable(),
}).meta({ ref: "PluginArchGithubDiscoveryTreeEntry" })
export const githubDiscoveryTreeResponseSchema = pluginArchListResponseSchema("PluginArchGithubDiscoveryTreeResponse", githubDiscoveryTreeEntrySchema)
export const githubDiscoveryApplyResponseSchema = pluginArchMutationResponseSchema(
  "PluginArchGithubDiscoveryApplyResponse",
  z.object({
    autoImportNewPlugins: z.boolean(),
    createdMarketplace: marketplaceSchema.nullable().optional(),
    connectorInstance: connectorInstanceSchema,
    connectorTarget: connectorTargetSchema,
    createdPlugins: z.array(pluginSchema),
    createdMappings: z.array(connectorMappingSchema),
    materializedConfigObjects: z.array(configObjectSchema),
    sourceRevisionRef: z.string().trim().min(1),
  }),
)
export const githubInstallStartResponseSchema = pluginArchMutationResponseSchema(
  "PluginArchGithubInstallStartResponse",
  z.object({
    redirectUrl: z.string().url(),
    state: z.string().trim().min(1),
  }),
)
export const githubInstallCompleteResponseSchema = pluginArchMutationResponseSchema(
  "PluginArchGithubInstallCompleteResponse",
  z.object({
    connectorAccount: connectorAccountSchema,
    repositories: z.array(githubRepositorySchema),
  }),
)
export const githubSetupResponseSchema = pluginArchMutationResponseSchema(
  "PluginArchGithubSetupResponse",
  z.object({
    connectorAccount: connectorAccountSchema,
    connectorInstance: connectorInstanceSchema,
    connectorTarget: connectorTargetSchema,
  }),
)
export const githubValidateTargetResponseSchema = pluginArchMutationResponseSchema(
  "PluginArchGithubValidateTargetResponse",
  z.object({
    branchExists: z.boolean(),
    defaultBranch: z.string().trim().min(1).nullable(),
    repositoryAccessible: z.boolean(),
  }),
)